代码之家  ›  专栏  ›  技术社区  ›  Roee Adler

C#:如何设置分部类中属性的默认值?

  •  20
  • Roee Adler  · 技术社区  · 16 年前

    我对C#很陌生,所以请容忍我。。。

    public partial class SomeModel
    {
        public bool IsSomething { get; set; }
        public List<string> SomeList { get; set; }
    
        ... Additional methods using the above data members ...
    }
    

    我想初始化两个数据成员: IsSomething True SomeList new List<string>()

    实现这一目标的最佳方式是什么?

    谢谢

    PS我在ASP.NETMVC中工作,为某个模型添加功能,因此是分部类。

    8 回复  |  直到 16 年前
        1
  •  41
  •   Community Mohan Dere    9 年前

    更新为C#6

    // Initialize to a string literal
    public string SomeProperty {get;set;} = "This is the default value";
    
    // Initialize with a simple expression
    public DateTime ConstructedAt {get;} = DateTime.Now;
    
    // Initialize with a conditional expression
    public bool IsFoo { get; } = SomeClass.SomeProperty ? true : false;
    

    原始答案

    自动实现的属性可以在类构造函数中初始化,但不能在属性本身上初始化。

    public SomeModel
    {
        IsSomething = false;
        SomeList = new List<string>();
    }
    

    private bool _IsSomething = false;
    public bool IsSomething
    {
        get { return _IsSomething; }
        set { _IsSomething = value; }
    }
    

    更新: Mehrdad's answer

        2
  •  9
  •   Reed Copsey    16 年前

    第一个属性(IsSomething)是布尔值。默认情况下,它将为false。

    首先,使用备份存储字段:

    private bool isSomething = true;
    public bool IsSomething {
        get { return this.isSomething; }
        set { this.isSomething = value; }
    }
    

    第二个选项-将其添加到构造函数中。

    请注意,第一个选项没有额外的开销——这基本上是编译器在使用自动属性时所做的事情。

        3
  •  6
  •   Mehrdad Afshari    16 年前

    在一个分部类的两个部分中不能有两个构造函数。但是,您可以使用 partial methods

    // file1:
    partial void Initialize();
    public Constructor() {
        // ... stuff ... initialize part 1
        Initialize();
    }
    
    // file2:
    void Initalize() {
        // ... further initializations part 2 might want to do
    }
    

    如果分部类的任何部分都没有定义分部方法,那么对它的所有调用都将被忽略。

        4
  •  5
  •   Simon_Weaver    15 年前

    如果您试图将属性添加到WCF代理类(通过添加服务引用生成),您可能会惊讶地发现私有字段没有初始化,因为 no constructor at all is called .

        private bool _sendEmail = true;
    

    这与字段是否在分部类中无关。

    [OnDeserialized] 属性,用于对对象执行进一步初始化。这是System.Runtime.Serialization的一部分,因此仅在使用 DataContractSerializer .

    public partial class EndOfDayPackageInfo
    {
        [OnDeserialized()]
        public void Init(StreamingContext context)
        {
            _sendEmail = true;
        }
    
        private bool _sendEmail;
        public bool SendEmail
        {
            get
            {
                return _sendEmail;
            }
            set
            {
                _sendEmail = value;
                RaisePropertyChanged("SendEmail");
            }
        }
    

    另一种方法是“延迟加载”属性,但这种方法不那么优雅。

        private bool _sendEmail;
        private bool _sendEmailInitialized;
    
        public bool SendEmail
        {
            get
            {
                if (!_sendEmailInitialized)
                {
                    _sendEmailInitialized = true;
                    _sendEmail = true;  // default value
                }
    
                return _sendEmail;
            }
            set
            {
                if (!_sendEmailInitialized)
                {
                    // prevent unwanted initialization if 'set' is called before 'get'
                    _sendEmailInitialized = true;
                }
    
                _sendEmail = value;
                RaisePropertyChanged("SendEmail");
            }
        }
    
        5
  •  4
  •   Gregoire    16 年前

    对此,不要使用自动属性,而是使用旧方法

    YourType _yourParameter = yourDefaultValue;
    public YourType YourParameter
    {
       get{return _yourParameter;}
       set{_yourParameter=value;}
    }
    
        6
  •  3
  •   Ant    10 年前

    对于C#6.0版的用户,可以如下初始化属性:

    public bool IsSomething { get; set; } = true;
    public List<string> SomeList { get; set; } = new List<string>();
    
        7
  •  1
  •   Paul Turner    16 年前

    这两个属性都已具有所需的默认值。

    在分部类中使用构造函数没有什么错。除了源代码分布在多个文件/声明中之外,分部类没有任何特殊之处。

        8
  •  0
  •   Subhamay    8 年前
     private bool _InternalUserContactUpdate = false;
            public bool InternalUserContactUpdate
            {
                get { return _InternalUserContactUpdate; }
                set { _InternalUserContactUpdate = value; }
            }
    

    然后,当您要覆盖条件上的值时,

    if(!objUserModel.FirstName.ToLower().Equals(entry.Key[0].Attributes.Contains("firstname").ToString().ToLower()))
            {
                 objUserModel.InternalUserContactUpdate= true;
            }
    

    希望这会有所帮助