2017-04-25 107 views
0

我創建瞭如下的屬性,並且指定的默認值不起作用。爲自動屬性設置的默認值不起作用

[DefaultValue(100)] 
public int MyProperty 
{ 
    get; 
    set; 
} 

但屬性不返回指定的默認值,而是返回「O」

任何人都可以請澄清我嗎?

問候,

+0

按照此鏈接:http://stackoverflow.com/questions/40730/how-do-you-give-ac-sharp-auto-property-a-default-value – Kingsman

回答

1

您使用的是DefaultValue屬性。

DefaultValueAttribute不會使用該屬性的值自動初始化成員。您必須在代碼中設置初始值。

https://msdn.microsoft.com/en-us/library/system.componentmodel.defaultvalueattribute(v=vs.110).aspx

在C#5以下的,給予屬性的默認值,你必須做它在構造函數中。

public class MyClass 
{ 
    public MyClass() { 
     MyProperty = 100; 
    } 

    public int MyProperty {get; set;} 
} 

在C#版本6(及以上),你可以這樣做:

public int MyProperty { get; set; } = 100; 
1

如果您正在使用C#6.0,你可以用它來設置默認屬性值:

public int MyProperty { get; set; } = 100; 
+0

有沒有必要張貼我的答案 – Alex

+0

當我發佈時,你的回答只有關於DefaultValue屬性的信息。 – barzozwierz