C#中的属性设置身体没有声明类级属性变量 [英] c# property setter body without declaring a class-level property variable
问题描述
我需要声明一个类级变量来持有物业,或者我可以只参照的自己。{PROPERTYNAME}
中的getter / setter?
在换句话说,我可以做到这一点? (在这里我还没有定义 mongoFormId
的任何地方):
公共字符串mongoFormId
{
获得
{
返回this.mongoFormId;
}
组
{
this.mongoFormId =价值;
revalidateTransformation();
}
}
您既可以使用自动存取或的实现自己的。如果您使用自动访问,C#编译器会产生一个后备字段为你,但如果你实现你自己的,你必须手动提供支持字段(或办理值一些其他的方式)。
私人字符串_mongoFormId;
公共字符串mongoFormId
{
{返回this._mongoFormId; }
组
{
this._mongoFormId =价值;
revalidateTransformation();
}
}
更新:由于这有人问,C#6.0已经发布。然而,即使href=\"https://msdn.microsoft.com/en-us/magazine/dn802602.aspx\" rel=\"nofollow\">新语法选项的 Do I need to declare a class-level variable to hold a property, or can I just refer to In other words, can I do this? (where I haven't defined
You can either use automatic accessors or implement your own. If you use automatic accessors, the C# compiler will generate a backing field for you, but if you implement your own you must manually provide a backing field (or handle the value some other way). UPDATE: Since this question was asked, C# 6.0 has been released. However, even with the new syntax options, there is still no way to provide a custom setter body without the need to explicitly declare a backing field. 这篇关于C#中的属性设置身体没有声明类级属性变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!self.{propertyname}
in the getter/setter?mongoFormId
anywhere):public string mongoFormId
{
get
{
return this.mongoFormId;
}
set
{
this.mongoFormId = value;
revalidateTransformation();
}
}
private string _mongoFormId;
public string mongoFormId
{
get { return this._mongoFormId; }
set
{
this._mongoFormId = value;
revalidateTransformation();
}
}