是否有可能迫使一个自动属性以使用只读支持字段? [英] Is it possible to force an auto-property to use a readonly backing field?

查看:186
本文介绍了是否有可能迫使一个自动属性以使用只读支持字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的项目包含了大量的类与特性的支持字段被标记只读因为它们只设置在施工。作为一个风格问题,我喜欢使用自动属性,因为它消除了大量的样板code和鼓励使用该属性成员,而不是支持字段的。然而,使用自动属性时我失去了只读性我的支持领域。据我所知,编译器/运行时能够采取的一些性能增强的优势,当一个字段被标记这样,所以我希望能够记住我的自动属性为只读,这样的事情:

  [只读]
公共字符串名字{获得; }
 

而不是

 私人只读字符串_LastName;
公共字符串名字
{
    得到
    {
        返回_LastName;
    }
}
 

有一些机制已经可以做到这一点?如果没有,是从自定义支持字段的性能提升是只读真的值得吗?

揭场公众是另一种选择,我想,它只是似乎错了,露出一个字段的方式。即。

 公共只读字符串姓氏;
 

解决方案

恐怕不行,但是你可以这样做:

 公共字符串名字{获得;私定; }
 

不太一样好只读,但不是太糟糕了。

My project contains a large number of classes with properties whose backing field is marked readonly as they are only set at construction. As a matter of style, I like using auto-properties as it eliminates a lot of boilerplate code and encourages use of the property member rather than the backing field. However, when using an auto-property I lose the "readonly-ness" of my backing field. I understand the compiler/runtime is able to take advantage of some performance enhancements when a field is marked this way, so I would like to be able to mark my auto-property as readonly, something like this:

[ReadOnly]
public string LastName { get; }

rather than

private readonly string _LastName;
public string LastName 
{ 
    get
    { 
        return _LastName;
    }
}

Is there some mechanism already available to do this? If not, is the performance gain from the custom backing field being readonly really worthwhile?

Exposing the field as public is another option, I suppose, it just seems wrong to expose a field that way. i.e.

public readonly string LastName;

解决方案

I'm afraid not, but you can do this:

public string LastName { get; private set; }

Not quite as good as readonly, but not too bad.

这篇关于是否有可能迫使一个自动属性以使用只读支持字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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