括号中初始化的值是否会覆盖 C# 构造函数中设置的值?

Do values initialized in brackets override those set in C# constructor?

如果在创建新 class 的代码中启动初始列表,有人可以解释我将如何在 C# class 构造函数中添加 GENERATED 通知。 Notifications = notificationsPASSEDList在构造函数之后只有运行吗?

//.. get list of notifications to pass
var myClass = new MyClass { Notifications = notificationsPASSEDList }

public class MyClass {

    public List<NotificationsClass> Notifications;

    public MyClass () {
        // .. get list of generated notifications
        Notifications.AddRange(notificationsGENERATEDList)
    }

}

可以按照您的要求进行操作,但这不是一个好主意,因为您必须修改通知 属性 以便分配给它执行添加而不是分配,这非常规且令人困惑。但是给你:

public class MyClass {

    public List<NotificationsClass> _notifications;

    public MyClass()
    {
        _notifications = notificationsGENERATEDList;
    }

    public Notifications
    {
        get { return _notifications; }
        set { _notifications.AddRange(value); }
    }
}

更好的方法是在构造函数中传递 PASSEDlist 而不是使用初始化语法:

public class MyClass {

    public List<NotificationsClass> Notifications;

    public MyClass(List<NotificationClass> passedList)
    {
        Notifications = notificationsGENERATEDList;
        Notifications.Add(passedList);
    }
}

然后调用它:

var myClass = new MyClass( notificationsPASSEDList);

好吧,在设置属性时,您可以检查列表中是否存在任何内容(肯定会添加到构造函数中)并保存它们:

    private generated = null;
    private List<NotificationsClass> notifications;
    public List<NotificationsClass> Notifications 
    {
        get 
        {
             return notifications;
        }
        set
        {
            if(generated != null)
            {
                notifications = generated ;
                notifications.AddRange(value);
                generated = null
             }
             else
                notifications = value;
        }

    }

public MyClass () {
        generated = notificationsGENERATEDList;
    }

请注意,private guaranteed = null; 行可能看起来是多余的,但它的存在是为了确保并非总是分配列表会实际将其附加到列表中,并且只有在有保证列表时才会添加。否则只会分配它。

如果你想一直保留保证列表,那么你可以更改这部分代码:

if(guaranteed != null)
{
    notifications = generated ;
    notifications.AddRange(value);
    generated = null;
}
else
    notifications = value;

对此:

if(generated != null)
{
     notifications = generated;
     notifications.AddRange(value);
}
else
    notifications = value;