c#中的高级枚举

本文关键字:枚举 高级 | 更新日期: 2023-09-27 18:17:52

所以我在c#中第一次使用枚举,但我不认为它会持续下去,因为我刚刚意识到你在Java中缺乏灵活性。

例如,我想在Java中做的等效操作是这样的:

public enum Days {
    Mon("Monday"), Tue("Tuesday"), Wed("Wednesday"), Thu("Thursday", 93), Fri, Sat("Saturday", 44), Sun;
    private String longName;
    private int other;
    Days() {}
    Days(String longName) {
        this.longName = longName;
    }
    Day(String longName, int somethingElse) {
        this(longName);
        this.other = somethingElse;
    }
    @Override
    public String toString() {
        return this.longName + ", " + this.other;
    }
}

我可以在c#中做这个吗?据我所知,对于枚举,您只能执行如下操作:

public enum Days { Mon=1, Tue=2, Wed=3 }

它不需要是一个严格的枚举,只要像Java的枚举一样就可以了。

c#中的高级枚举

你可以给enum添加一个显示名:

public enum Days {
    [Display(Name = "Monday")]
    Mon=1, 
    [Display(Name = "Tuesday")]
    Tue=2, 
    [Display(Name = "Wednesday")]
    Wed=3 
}

但它只是元数据。你不能像在Java中那样给它们添加实现。

可以使用具有静态只读属性的类:

public class Days {
    private String longName;
    private int other;
    Days() {}
    Days(String longName) 
    {
        this.longName = longName;
    }
    Days(String longName, int somethingElse) 
        : this(longName) 
    {
        this.other = somethingElse;
    }
    public override String ToString() 
    {
        return this.longName + ", " + this.other;
    }
    // just an example - in reality you'd probably want to keep one instance for each property in a static dictionary.
    public static Days Mon {get{return new Days("Monday",1);}}
    public static Days Tue {get{return new Days("Tuesday",2);}}
    // etc.
}

但是它和"真"enum有显著的区别

使用Extension Method可以为enum添加额外的功能。

public enum Days {
    MON =1,
    TUE=2,
    WED=3,
    THUR=4,
    FRI=5,
    SAT=6,
    SUN=7
}
public static class EnumTypeExtensions {
    public static string FriendlyString(this Days day) {
        switch (day) {
            case Days.MON:
                return "Monday";
            case Days.TUE:
                return "Tuesday";
            ...
        }
    }
}

//Usage-Example:
public void test() {
    Days tuesday = Days.TUE;
    string s = tuesday .FriendlyString();
    //s == "Tuesday"
}