【问题标题】:Do values initialized in brackets override those set in C# constructor? [duplicate]括号中初始化的值是否会覆盖 C# 构造函数中设置的值? [复制]
【发布时间】:2020-02-21 07:50:43
【问题描述】:

如果在创建新类的代码中启动了初始列表,有人可以解释我将如何在 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)
    }

}

【问题讨论】:

  • 试试看吧!

标签: c# public


【解决方案1】:

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

    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;

【讨论】:

    【解决方案2】:

    可以按照您的要求做,但这不是一个好主意,因为您必须修改 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);
    

    【讨论】:

      猜你喜欢
      • 2023-03-05
      • 2020-12-01
      • 1970-01-01
      • 2012-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-09
      • 1970-01-01
      相关资源
      最近更新 更多