열거 형 및 일치하는 속성에 대한 C # 명명 규칙
나는 종종 자신의 상태 속성을 열거 형으로 유지하는 클래스를 구현하는 것을 발견합니다. 상태 열거 형과 상태 유형의 ONE 상태 속성이 있습니다. 이 이름 충돌을 어떻게 해결해야합니까?
public class Car
{
public enum Status
{
Off,
Starting,
Moving
};
Status status = Status.Off;
public Status Status // <===== Won't compile =====
{
get { return status; }
set { status = value; DoSomething(); }
}
}
Status 열거 형이 다른 유형에 공통적이라면 클래스 외부에두면 문제가 해결 될 것입니다. 그러나 Status는 Car에만 적용되므로 클래스 외부에서 열거 형을 선언하는 것은 의미가 없습니다.
이 경우 어떤 명명 규칙을 사용합니까?
주의 :이 질문은 일부의 답변의 의견에 논란이 된 이 질문 . 주요 질문 이 아니기 때문에 가시성이별로 없었습니다.
편집 : Filip Ekberg는 '상태'의 특정 경우에 대한 IMO 훌륭한 해결 방법을 제안합니다. 그러나 Michael Prewecki의 답변 에서와 같이 열거 형 / 속성의 이름이 다른 솔루션에 대해 읽으면 흥미로울 것 입니다.
EDIT2 (2010 년 5 월) : 내가 가장 좋아하는 솔루션은 Chris S가 제안한대로 열거 형 유형 이름을 복수화하는 것입니다. MS 지침에 따르면 플래그 열거 형에만 사용해야합니다. 하지만 점점 더 좋아하게되었습니다. 이제 일반 열거 형에도 사용합니다.
나는 토론에 1 유로를 추가 할 것이지만 아마도 새로운 것을 추가하지 않을 것입니다.
확실한 해결책은 Status를 중첩 된 Enum에서 제거하는 것입니다. 대부분의 .NET 열거 형 (Windows.Forms 네임 스페이스의 일부 제외)은 중첩되지 않으며 API를 사용하는 개발자가 클래스 이름을 접두사로 지정해야하는 데 불편 함을줍니다.
언급되지 않은 한 가지는 MSDN 지침에 따른 플래그 열거 형 은 이미 알고 있는 복수형 명사 여야한다는 것입니다 (상태는 단순 열거 형이므로 단수 명사를 사용해야 함).
State (State라고하는 열거 형)는 어휘이며 "Status"는 대부분의 우리 언어와 같은 영어가 라틴어에서 흡수 한 명사의 명사입니다. Vocative는 조건에 대해 명사를 명명하는 것이며 명사는 동사의 주제입니다.
즉, 자동차 가 움직일 때 동사가 움직이고있는 것이 그 상태입니다. 그러나 차는 꺼지지 않고 엔진이 작동합니다. 엔진이 시작되지도 않고 엔진도 작동합니다 (여기에서 예제를 선택했기 때문에 관련이 없을 수 있습니다).
public class Car
{
VehicleState _vehicleState= VehicleState.Stationary;
public VehicleState VehicleState
{
get { return _vehicleState; }
set { _vehicleState = value; DoSomething(); }
}
}
public enum VehicleState
{
Stationary, Idle, Moving
}
State is such a generalised noun wouldn't it be better to describe what state it is referring to? Like I did above
The type example also in my view doesn't refer to the reader type, but its database. I would prefer it if you were describing the reader's database product which isn't necessarily relevant to the type of reader (e.g. the type of reader might be forward only, cached and so on). So
reader.Database = Databases.Oracle;
In reality this never happens as they're implemented as drivers and an inheritance chain instead of using enums which is why the line above doesn't look natural.
The definition of "Off", "Starting" and "Moving" is what i would call a "State". And when you are implying that you are using a "State", it is your "Status". So!
public class Car
{
public enum State
{
Off,
Starting,
Moving
};
State state = State.Off;
public State Status
{
get { return state ; }
set { state= value; DoSomething(); }
}
}
If we take another example from the one stated where you'd like to use the word "Type" such in this case:
public class DataReader
{
public enum Type
{
Sql,
Oracle,
OleDb
}
public Type Type { get; set; } // <===== Won't compile =====
}
You really need to see that there is a difference between enums and enums, right? But when creating a framework or talking about architecture you need to focus on the simillarities, ok lets find them:
When something is set to a State, it's defined as the "things" Status
Example: The Car's Status is in Running State, Stopped State, and so on.
What you want to acheive in the second example is somewhat this:
myDataReader.Type = DataReader.Database.OleDb
You might think that this says against what i've been preaching about to others, that you need to follow a standard. But, you are following a standard! The Sql-case is a specific case aswell and therefore need a somewhat specific solution.
However, the enum would be re-usable within your System.Data
space, and that's what the patterns is all about.
Another case to look at with the "Type" is "Animal" where Type defines the Species.
public class Animal
{
public enum Type
{
Mammal,
Reptile,
JonSkeet
}
public Type Species{ get; set; }
}
This is following a pattern, you don't specificly need to "know" the Object for this and you are not specifing "AnimalType" or "DataReaderType", you can re-use the enums in your namespace of choice.
I think the real problem here is that the enum Status is encapsulated within your class, such that Car.Status
is ambiguous to both the property Status
and the enum Status
Better yet, put your enum outside of the class:
public enum Status
{
Off,
Starting,
Moving
}
public class Car
{
public Status Status
{ ... }
}
UPDATE
Due to the comments below, I'll explain my design above.
I'm one who doesn't believe that enums or classes or any other object should reside inside another class, unless it will be totally private within that class. Take the above example, for instance:
public class Car
{
public enum Status
{...}
...
public Status CarStatus { get; set;}
}
While some commenters would argue that Status doesn't have any meaning outside the scope of the class Car, the fact that you are setting a public property means that there are other parts of the program that will use that enum:
public Car myCar = new Car();
myCar.CarStatus = Car.Status.Off;
And that to me is a code smell. If I'm going to look at that status outside of Car
, I might as well define it outside as well.
As such, I will probably just rename it as:
public enum CarStatus
{...}
public class Car
{
...
public CarStatus Status { get; set; }
}
However, if that enum will be used within and only within the car class, then I'm fine with declaring the enum there.
I know my suggestion goes against the .NET Naming conventions, but I personally prefix enums with 'E' and enum flags with 'F' (similar to how we prefix Interfaces with 'I'). I really do not understand why this is not the convention. Enums/Flags are a special case like Interfaces that will never change their type. Not only does it make it clear what it is, it's very easy to type in intellisense since the prefix will filter most other types/variables/etc, and you won't have these naming clashes.
And that would also solve another problem where for examples in WPF they use static classes like enums (e.g. FontWeights) that have pre-defined instances of types but you would not know if you don't search for it. If they just prefixed them with 'E', all you would have to do is type on character to find these special static classes.
Haters of Hungarian notation and its variants be damned. I use a convention of suffixing enums with - wait for it - Enum
. I consequently never have the problem you describe, waste time worrying about what to call them and the code is readable and self-descriptive to boot.
public class Car
{
public enum StatusEnum
{
Off,
Starting,
Moving
};
public StatusEnum Status { get; set; }
}
I'd change the name of the property to something like "CurrentStatus". Quick an easy :)
I suggest adding "Option" to the type name (or Flag if it contains bit flags), i.e. type is Car.StatusOption and property is Car.Status.
Compared to pluralizing, this avoids naming collisions when creating collections of the enum type, where you would normally want to pluralize the collection property, not the enum type.
I usually prefix the enums, e.g. CarStatus. I suppose it all depends on team you're working with (if they have any rules/ processes for that sort of thing) and the objects usage. Just my 2 cents (:
참고URL : https://stackoverflow.com/questions/495051/c-sharp-naming-convention-for-enum-and-matching-property
'program story' 카테고리의 다른 글
Ajax와 같은 비동기 호출을 호출하는 동안 코드를 대기시키는 방법 (0) | 2020.09.06 |
---|---|
Flash없이 클립 보드에 복사 (0) | 2020.09.06 |
마우스 오버시 rgba 배경색의 알파 만 변경할 수 있습니까? (0) | 2020.09.06 |
rsync와 양방향 동기화 (0) | 2020.09.06 |
NuGet 패키지에 클래스 라이브러리 용 Xml 문서를 어떻게 포함하나요? (0) | 2020.09.06 |