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



有人能解释一下,如果在创建新类的代码中启动了初始列表,我将如何在C#类构造函数中添加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)
}
}

可以按照您的要求执行,但这不是一个好主意,因为您必须修改Notifications属性,以便为其赋值执行添加而不是赋值,这是非常规的,令人困惑。但你来了:

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;

最新更新