Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
310 views
in Technique[技术] by (71.8m points)

c# - 为C#自动属性赋予初始值的最佳方法是什么?(What is the best way to give a C# auto-property an initial value?)

How do you give a C# auto-property an initial value?

(如何为C#自动属性赋予初始值?)

I either use the constructor, or revert to the old syntax.

(我要么使用构造函数,要么恢复为旧语法。)

Using the Constructor:

(使用构造函数:)

class Person 
{
    public Person()
    {
        Name = "Initial Name";
    }
    public string Name { get; set; }
}

Using normal property syntax (with an initial value)

(使用常规属性语法 (带有初始值))

private string name = "Initial Name";
public string Name 
{
    get 
    {
        return name;
    }
    set
    {
        name = value;
    }
}

Is there a better way?

(有没有更好的办法?)

  ask by bentford translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In C# 5 and earlier, to give auto implemented properties an initial value, you have to do it in a constructor.

(在C#5和更早版本中,要为自动实现的属性提供一个初始值,您必须在构造函数中进行设置。)

Since C# 6.0, you can specify initial value in-line.

(从C#6.0开始,您可以内联指定初始值。)

The syntax is:

(语法为:)

public int X { get; set; } = x; // C# 6 or higher

DefaultValueAttribute is intended to be used by the VS designer (or any other consumer) to specify a default value, not an initial value.

(VS设计器(或任何其他使用者)打算使用DefaultValueAttribute来指定默认值,而不是初始值。)

(Even if in designed object, initial value is the default value).

((即使在设计对象中,初始值也是默认值)。)

At compile time DefaultValueAttribute will not impact the generated IL and it will not be read to initialize the property to that value (see DefaultValue attribute is not working with my Auto Property ).

(在编译时, DefaultValueAttribute不会影响生成的IL,也不会读取它来将属性初始化为该值(请参见DefaultValue属性不适用于我的Auto Property )。)

Example of attributes that impact the IL are ThreadStaticAttribute , CallerMemberNameAttribute , ...

(影响IL的属性示例包括ThreadStaticAttributeCallerMemberNameAttribute ,...)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...