С стиль C #: могут быть сгруппированы свойства с их прилагающимися полями?

StackOverflow https://stackoverflow.com/questions/6064636

Вопрос

Мне нравится организовать простые свойства, как это:

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