简体   繁体   English

在C#中初始化公共属性的最佳方法是什么?

[英]What's the best way to initialize a public property in C#?

我需要给属性赋初始值,我想知道是否有比使用构造函数更简单的方法。

Are you using automatically implemented properties? 您是否正在使用自动实现的属性? The value type properties will be initialized to their default values. 值类型属性将被初始化为其默认值。 Reference types will be initialized to null. 引用类型将初始化为null。

If you want them to initialize them to some other I think the best option is to set them in the constructor. 如果您希望它们将它们初始化为其他类型,我认为最好的选择是在构造函数中进行设置。

If you are not using automatically implemented properties you can initialize them where they are declared. 如果您不使用自动实现的属性,则可以在声明它们的地方对其进行初始化。

It will also be useful to keep in mind the order in which the objects fields and constructors are initialized. 记住对象字段和构造函数的初始化顺序也很有用

If you are taking advantage of automatic properties, the constructor is the easiest way. 如果要利用自动属性,则构造函数是最简单的方法。 If you are not, then your member variable can define the default value. 如果不是,则您的成员变量可以定义默认值。

private string _someString = "Hello.";

But, you'll have to define the getter and setter yourself. 但是,您必须自己定义getter和setter。

public string SomeString
{
    get { return _someString; }
    set { _someString = value; }
}

Which wouldn't be simpler than just defining the default in the constructor. 这比在构造函数中定义默认值简单得多。

If you just want to initialize the property values, then constructors are simply enough I don't see why you think they are not simple. 如果只想初始化属性值,那么构造函数就足够了,我不明白为什么您认为它们并不简单。

However you can do this if you want, you can initialize the variable like this : 但是,您可以根据需要执行此操作,可以像这样初始化变量:

int _myProperty = 5;
public int MyProperty
{
  get{ return _myProperty ;}

 set { _myProperty=value; }
}

I like to think about this a bit differently. 我想对此有所不同。 If the value is something that is mandatory for the creation of an instance, it needs to be a parameter for the constructor. 如果该值是创建实例所必需的值,则它必须是构造函数的参数。

However, if the value is optional then setting it via a property is fine. 但是,如果该值是可选的,则可以通过属性进行设置。

Well Constructors are best for doing this. 好的构造函数最适合这样做。 How ever u can call a methods too. 您怎么也可以调用方法。

Check following link too Initializing C# auto-properties 还要检查以下链接初始化C#自动属性

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM