C# 风格:属性可以与其支持字段分组吗?
我喜欢组织这样的简单属性:
private int foo;
public int Foo
{
get { return foo; }
set
{
// validate value
foo = value;
}
}
我一直在玩 StyleCop,它对我大喊大叫将字段放置在构造函数之后。只要该字段从未在属性之外被引用,这种样式是否被普遍接受?注:我意识到这涉及个人偏好,但我想知道在这个问题上是否存在普遍共识。
I like to organize simple properties like this:
private int foo;
public int Foo
{
get { return foo; }
set
{
// validate value
foo = value;
}
}
I've been playing around with StyleCop, and it yells at me for placing fields after constructors. Is this style generally accepted, as long as the field is never referenced outside of the property? Note: I realize that there is personal preference involved, but I am wondering if there is a general consensus regarding this issue.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
是的,这对我来说似乎很合理。
通常,我将所有字段和属性放在顶部,然后是构造函数,然后是方法 - 但如果您想将它们放在构造函数之后,这似乎也是合理的。
Yes, that seems reasonable to me.
Typically I put all the fields and properties at the top, then the constructors, then the methods - but if you want to put them after the constructors, that seems reasonable too.
如果您的属性将是简单的数据访问,请考虑使用自动属性:
编译器将代表您在幕后创建一个私有成员变量。
具体针对您的问题,不要过多关注 ReSharper 或 StyleCop 等工具。他们格式化代码的一些方式以及他们抱怨的事情确实是一个偏好问题。我不会将成员变量放在其公共属性附近,但我可以看到这会很方便。
If your properties are going to be simple data access consider using auto properties:
The compiler will create a private member variable behind the scenes on your behalf.
Specifically to your question, don't put too much stock in tools like ReSharper or StyleCop. Some of the ways they format code, and the things they complain about are truly a matter of preference. I do not put the member variables near their public properties, but I can see how this would be convenient.
可能?由于这只会影响您团队中的人员,因此您必须弄清楚他们认为什么是最好的并遵循它。 Style Cop 的建议往往有点……过分了。
我通常将它们放在属性之后,因为上面的空间是为文档保留的。
May? Since this only affects people on your team, you have to figure out what they think is best and go with that. Style Cop is often a bit... overboard on its recommendations.
I usually put them after the property, as the space above is reserved for documentation.
这可能是一个偏好问题,但这似乎比让他们与私人成员混合更好。
我通常使用嵌套区域来支持属性区域内的字段,因为它不会干扰 Visual Studio 注释,而且它们会分组在一起。
It may be a matter of preference, but this seems better than having them mixed with private members.
I usually use a nested region for backing fields inside the properties region since it doesn't interfere with visual studio comments and yet they are grouped toghether.