开发者

is there any property default value initializer attribute?

开发者 https://www.devze.com 2022-12-09 19:50 出处:网络
I need like this public class AA{ public AA(){} [Default(\"hi\")] 开发者_JS百科public string value1{get;set}

I need like this

public class AA{
   public AA(){}
   [Default("hi")]
   开发者_JS百科public string value1{get;set}
   [Default(12)]
   public int value2{get;set;}
}

Usage:

AA a=new AA();
print(a.value1);  //result: hi
print(a.value2);  //result: 12 

Is it possible to create like this?

I know another way

Public class AA{
   public AA(){value1="hi";value2=12}
   ...
}

Otherwise

AA a=new AA(){value1="hi",value2=12};

But i need only attribute.


No, but you can easily initialize them in your parameterless constructor.

public class AA
{
   public AA()
   {
      // default values
      Value1 = "hi";
      Value2 = 12;
   }

   public string Value1 {get;set}
   public int Value2 {get;set;}
}

Or, instead of using auto-implemented properties, use actual properties with backing fields initialized to a default value.

public class AA
{
   private string _value1 = "hi";
   public string Value1
   { get { return _value1; } }
   { set { _value1 = value; } }

   private int _vaule2 = 12;
   public int Value2
   { get { return _value2; } }
   { set { _value2 = value; } }
}

Creating a property with an actual backing field is not such a big problem with Visual Studio snippets. By typing prop in VS and hitting the Tab key, you get the full snippet for a read/write property.

[Edit] Check this thread also: How do you give a C# Auto-Property a default value?

[Yet another edit] If your believe this will make it more readable, check the following link: it's a get/set snippet which will generate the property with the necessary backing field, and automatically add a #region block around it to collapse the code: Snippets at CodePlex (by Omer van Kloeten). Download it and check the Get+Set Property (prop) snippet.


Not currently. Right now, the only options are to set this in the constructor, or to use a property with a backing field.

However, you could use PostSharp to implement this via AOP fairly easily. (Although, I do not believe this is currently an option).

0

精彩评论

暂无评论...
验证码 换一张
取 消