IT박스

C #의 열거 형 내부 메서드

itboxs 2020. 6. 26. 19:05
반응형

C #의 열거 형 내부 메서드


Java에서는 열거 형 안에 메소드를 가질 수 있습니다.

C #에 그러한 가능성이 있습니까? 아니면 문자열 모음입니까?

재정의를 시도했지만 ToString()컴파일되지 않습니다. 누군가 간단한 코드 샘플을 가지고 있습니까?


열거 형 유형에 대한 확장 메소드작성할 수 있습니다 .

enum Stuff
{
    Thing1,
    Thing2
}

static class StuffMethods
{

    public static String GetString(this Stuff s1)
    {
        switch (s1)
        {
            case Stuff.Thing1:
                return "Yeah!";
            case Stuff.Thing2:
                return "Okay!";
            default:
                return "What?!";
        }
    }
}

class Program
{


    static void Main(string[] args)
    {
        Stuff thing = Stuff.Thing1;
        String str = thing.GetString();
    }
}

열거 형에 대한 확장 방법을 작성할 수 있습니다.

방법 : 열거 형에 대한 새 메서드 만들기 (C # 프로그래밍 가이드)


또 다른 옵션은 Jimmy Bogard가 만든 Enumeration Class 를 사용하는 것 입니다.

기본적으로로부터 상속되는 클래스를 만들어야합니다 Enumeration. 예:

public class EmployeeType : Enumeration
{
    public static readonly EmployeeType Manager 
        = new EmployeeType(0, "Manager");
    public static readonly EmployeeType Servant 
        = new EmployeeType(1, "Servant");
    public static readonly EmployeeType Assistant
        = new EmployeeType(2, "Assistant to the Regional Manager");

    private EmployeeType() { }
    private EmployeeType(int value, string displayName) : base(value, displayName) { }

    // Your method...
    public override string ToString()
    {
        return $"{value} - {displayName}!";
    }
}

그런 다음 열거 형처럼 사용할 수 있으며 내부에 메소드를 넣을 수 있습니다 (다른 것들 중에서).

EmployeeType.Manager.ToString();
//0 - Manager
EmployeeType.Servant.ToString();
//1 - Servant
EmployeeType.Assistant.ToString();
//2 - Assistant to the Regional Manager

NuGet으로 다운로드 할 수 있습니다 .

Although this implementation is not native in the language, the syntax (construction and usage) is pretty close to languages that implement enums natively better than C# (Kotlin for example).


Nope. You can create a class, then add a bunch of properties to the class to somewhat emulate an enum, but thats not really the same thing.

class MyClass
{
    public string MyString1 { get{ return "one";} }
    public string MyString2 { get{ return "two";} }
    public string MyString3 { get{ return "three";} }

    public void MyMethod()
    {
        // do something.
    }
}

A better pattern would be to put your methods in a class separate from your emum.


Since I came across, and needed the exact opposite of enum to string, here is a Generic solution:

static class EnumExtensions {
    public static T GetEnum<T>(this string itemName) {
        return (T) Enum.Parse(typeof(T), itemName, true);
    }
}

This also ignores case and is very handy for parsing REST-Response to your enum to obtain more type safety. Hopefully it helps someone


C# Does not allow use of methods in enumerators as it is not a class based principle, but rather an 2 dimensional array with a string and value.

Use of classes is highly discouraged by Microsoft in this case, use (data)struct(ures) instead; The STRUCT is intended as a light class for data and its handlers and can handle functions just fine. C# and its compiler don't have the tracking and efficiency capabilities as one knows from JAVA, where the more times a certain class / method is used the faster it runs and its use becomes 'anticipated'. C# simply doesn't have that, so to differentiate, use STRUCT instead of CLASS.

참고URL : https://stackoverflow.com/questions/5985661/methods-inside-enum-in-c-sharp

반응형