如何为定义如下的属性设置默认值:
public int MyProperty { get; set; }
在VS2008(代码段)中使用“prop”[tab] [tab]。
是否有可能不退回“旧方式”?:
private int myProperty = 0; // default value
public int MyProperty
{
get { return myProperty; }
set { myProperty = value; }
}
感谢您的时间。 最好的问候。
答案 0 :(得分:9)
只需在构造函数中设置“默认”值即可。
public class Person
{
public Person()
{
this.FirstName = string.Empty;
}
public string FirstName { get; set; }
}
此外,它们被称为自动属性。
答案 1 :(得分:2)
我的偏好是“旧方式”,而不是构造函数中的init。如果您以后添加了另一个构造函数,则必须确保从中调用第一个构造函数,否则您的属性将被取消初始化。
答案 2 :(得分:2)
尽管这是一个较旧的主题,我想添加一些在C#中实现的新方法>弗斯。 6:
https://msdn.microsoft.com/de-de/library/bb384054.aspx
public int MyInt { get; set; } = 0;
public string MyString { get; set; } = "Lorem Ipsum";
答案 3 :(得分:0)
[默认值( “MyFirstName”)] public string FirstName {get;组; }