C#中的属性设置身体没有声明类级属性变量 [英] c# property setter body without declaring a class-level property variable

查看:254
本文介绍了C#中的属性设置身体没有声明类级属性变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要声明一个类级变量来持有物业,或者我可以只参照的自己。{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 self.{propertyname} in the getter/setter?

In other words, can I do this? (where I haven't defined mongoFormId anywhere):

public string mongoFormId 
{
    get
    {
        return this.mongoFormId;
    }
    set
    {
        this.mongoFormId = value;
        revalidateTransformation();
    }
}

解决方案

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).

private string _mongoFormId;

public string mongoFormId 
{
    get { return this._mongoFormId; }
    set 
    {
        this._mongoFormId = value;
        revalidateTransformation();
    }
}

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屋!

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