默认值设置为一个属性 [英] Set a default value to a property

查看:225
本文介绍了默认值设置为一个属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以设置一个默认值,而属性的身体? preferably与注解。

  [SetTheDefaultValueTo(真)
公共BOOL IsTrue运算{获得;组; }

[SetTheDefaultValueTo(假)]
公共BOOL IsFalse {获得;组; }

公共无效东西()
{
    VAR IsTrue运算= this.IsTrue;
    VAR isFalse = this.IsFalse;
}
 

解决方案

没有,没有内置的功能设置与元数据属性的值。您可以使用某种形式,将建立一个类的实例与反思,然后,可以设置的默认值的一家工厂。但在短期,你需要使用的构造函数(或现场制定者......这是提升到构造函数。)要设置默认值。

如果你有几个重载的constuctor你可能想看看构造函数链

顺便说一句...高度要求的功能的自动属性将是一个类似的结构...

 公共字符串myvalue的{获得;组; } =我的默认;
 

...这个当前不存在在C#中,但希望它会在未来的版本。

呵呵,它变得更有趣,因为人甚至要求这样的事情...

 公共字符串myvalue的{
    私人字符串_myValue;
    {返回_myValue? 我的默认; }
    集合{_myValue =价值; }
}
 

...的优点是,你可以控制领域的范围只能是入店的物业code,所以你不必担心任何东西在你的类的演奏与国家不使用的getter / setter。

Is it possible to set a default value without the body of a property? Preferably with annotations.

[SetTheDefaultValueTo(true)]
public bool IsTrue { get; set; }

[SetTheDefaultValueTo(false)]
public bool IsFalse { get; set; }

public void Something()
{
    var isTrue = this.IsTrue;
    var isFalse = this.IsFalse;
}

解决方案

No, there is no built in ability to set the value of a property with metadata. You could use a factory of some sort that would build instances of a class with reflection and then that could set the default values. But in short, you need to use the constructors (or field setters... which are lifted to the constructor.) To set the default values.

If you have several overloads for your constuctor you may want to look at constructor chaining.

BTW... a highly requested feature to the automatic properties would be for a construct similar to this...

public string MyValue { get; set; } = "My Default";

... this does not currently exist in C# but hopefully it will in some future version.

Oh, it gets more fun because people have even requested something like this...

public string MyValue {
    private string _myValue;
    get { return _myValue ?? "My Default"; }
    set { _myValue = value; }
}

... the advantage being that you could control the scope of the field to only be accesible in the property code so you don't have to worry about anything else in your class playing with the state without using the getter/setter.

这篇关于默认值设置为一个属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆