如何从自定义属性获取枚举成员列表?

时间:2013-10-31 10:14:12

标签: c# enums custom-attributes

我有:

(1)类型枚举如:

public enum Types : int
{
[ParametrizedContentTypeAttribute(typeOf(Type1ParamEnum))]
Type1 = 10,

[ParametrizedContentTypeAttribute(typeOf(Type2ParamEnum))]
Type2 = 20,

[ParametrizedContentTypeAttribute(typeOf(Type3ParamEnum))]
Type3 = 30
}

(2)参数枚举

public enum Type1ParamEnum : int
{
Type1Param1 = 10,
Type1Param2 = 20,
Type1Param3 = 30
}

public enum Type2ParamEnum : int
{
Type2Param1 = 10,
Type2Param2 = 20,
Type2Param3 = 30
}

public enum Type3ParamEnum : int
{
Type3Param1 = 10,
Type3Param2 = 20,
Type3Param3 = 30
}

(3)自定义属性

[AttributeUsage(AttributeTargets.Field, AllowMultiple = false, Inherited = true)]
    public class ParametrizedContentTypeAttribute : DescriptionAttribute
    {
        public ParametrizedContentTypeAttribute(Type parametersType)
        {
            ParametersType = parametersType;
        }

        public Type ParametersType { get; private set; }
    }

如果我从1知道类型枚举成员的ID,如何从2获取Enums的可用成员列表。?

1 个答案:

答案 0 :(得分:0)

也许它可以通过使用类来伪造,就像在Java中一样。 名称很糟糕,结果值重叠,所以你必须弄清楚要正确计算它们,但这应该让你开始:

// Example model
public enum enumBuilding { Hotel, House, Skyscraper };
public enum enumFloor { Basement, GroundFloor, Penthouse };
public enum enumRoom { Entry, Office, Toilet };

public abstract class EnumArray
{
    static protected Building[] buildings;

    static EnumArray()
    {
        buildings = new Building[Enum.GetValues(typeof(enumBuilding)).Length];

        for (int i = 0; i < buildings.Length; i++)
            buildings[i] = new Building(i);
    }

    public static Building Hotel { get { return buildings[0]; } }
    public static Building House { get { return buildings[1]; } }
    public static Building Skyscraper { get { return buildings[2]; } }
}

public class Building
{
    protected Floor[] floors;

    public Building(int start)
    {
        floors = new Floor[Enum.GetValues(typeof(enumFloor)).Length];

        for (int i = 0; i < floors.Length; i++)
            floors[i] = new Floor(start + i * floors.Length);
    }

    public Floor Basement { get { return floors[0]; } }
    public Floor GroundFloor { get { return floors[1]; } }
    public Floor Penthouse { get { return floors[2]; } }
}

public class Floor
{
    protected int[] rooms;

    public Floor(int start)
    {
        rooms = new int[Enum.GetValues(typeof(enumRoom)).Length];

        for (int i = 0; i < rooms.Length; i++)
            rooms[i] = new Room(start + i * rooms.Length);
    }

    public int Entry { get { return rooms[0]; } }
    public int Office { get { return rooms[1]; } }
    public int Toilet { get { return rooms[2]; } }
}

        var index = EnumArray.Hotel.Basement.Office;