C#中的高级枚举

时间:2015-10-14 15:25:53

标签: c# enums

所以我第一次在C#中使用Enumerations,但我不认为它会持久,因为我刚刚意识到你在Java中缺乏灵活性。

例如,我想用Java做的事情就像这样:

select products.id, data, name, count(sells.id) as sell_count
from products 
left join sells on sells.product_id=products.id 
where user= ?
group by products.id

无论如何我能在C#中做到这一点吗?据我所知,使用枚举,您只能执行以下操作:

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;
    }
}

它不必严格地是枚举,就像Java枚举一样。

2 个答案:

答案 0 :(得分:2)

您可以在枚举中添加显示名称

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.

}

但它只是元数据。你不能像Java(显然)那样在Java中添加实现。

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

=$A11=0

但它与真正的"之间存在显着差异。枚举。

答案 1 :(得分:0)

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";