【问题标题】:How do you give a C# Auto-Property a default value When the Property is a Class当属性是类时,如何为 C# 自动属性赋予默认值
【发布时间】:2016-08-29 22:12:24
【问题描述】:

有一个类似的问题here。但是,我的属性不是intstring,而是class 本身,它有许多自己的属性。所以我想将默认值设置为属性的属性。

这是我的例子:

public class Claim
{
    public Person Member { get; set; }
    public Person Claimant { get; set; }
}

如您所见,我的属性不是intstring,而是Person。每个人都有很多属性,我想为每个对象设置其中一个的默认值。

例如,如果我像这样新建一个人:

Person Pete = new Person { PersonTypeID = 1 };

如您所见,Person 有一个 PersonTypeID 属性。可以说,每次实例化 Claim 类时,我想将该值设置为 Member1Claimant2 作为默认值。我该怎么做?

【问题讨论】:

  • 当您初始化Claim 时,编译器会自动将属性分配为其默认值。

标签: c#


【解决方案1】:

从C#6开始你可以初始化auto-implemented properties:

public Person Member { get; set; } = new Person { PersonTypeID = 1 }; // or by using the constructor of Person
public Person Claimant { get; set; } = new Person { PersonTypeID = 2 };

否则使用Claim的构造函数。

【讨论】:

    【解决方案2】:

    偷懒试试

    public class Claim
    {
        public Person Member { get; set; }
        public Person Claimant { get; set; }
    
        public Claim()
        {
            this.Member = new Person() { PersonTypeID = 1 };
            this.Claimant = new Person() { PersonTypeID = 2 };
        }
    }
    

    public class Claim
    {
        public Person Member { get; set; }
        public Person Claimant { get; set; }
    
        public Claim(int MemberTypeID, int ClaimantTypeID)
        {
            this.Member = new Person() { PersonTypeID = MemberTypeID };
            this.Claimant = new Person() { PersonTypeID = ClaimantTypeID };
        }
    }
    

    【讨论】:

    • 或 IoC 方式:在 ctor 中注入 Person 实例,或提供工厂方法,或 ...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-11
    相关资源
    最近更新 更多