我喜欢组织这样的简单属性:

private int foo;
public int Foo
{
    get { return foo; }
    set
    {
        // validate value
        foo = value;
    }
}
.

我一直在玩 stylecop ,它对我在构造函数之后放置字段。这种风格普遍接受,只要该领域从未在房产之外引用?注意:我意识到涉及个人偏好,但我想知道是否有关于这个问题的一般性共识。

有帮助吗?

解决方案

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.

其他提示

If your properties are going to be simple data access consider using auto properties:

public int Foo { get; set; }

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.

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.

// placed up here, it looks kinda weird, imho
// private int foo;
/// <summary>
/// The index of the Foo in the <see cref="Bar"/>
/// </summary>
public int Foo
{
    get { return foo; }
    set
    {
        // validate value
        foo = value;
    }
}
private int foo;

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top