当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - Enumeration Member Data Type

问题描述:

Is there any way to assign data type to enum members;

for example;

 public enum CarPartEnum

{

[string]

Color,

[int]

Speed

}

Why I want to do this?

Because the way it is recorded in the database, there is a CarProperties table.

And there is a key-value pair in the table.

Key: Color, Value: Red;

Key: Speed, Value: 250

So When I read it from database I would want to cast key to CarPartEnum and value to correct data type.

网友答案:

Maybe custom attribute like this:

public class MyTypeAttribute : Attribute
    {
        private readonly Type Type;
        public MyTypeAttribute (Type type)
        {
            Type = type;
        }
        public override string ToString()
        {
            return Type.ToString();
        }
    }

And use it like this:

public enum CarPartEnum
{
    [MyType(typeof(string))]
    Color,
    [MyType(typeof(int))]
    Speed
}

But I agree with Oded's answer that you should use custom class that mirrors your database.

网友答案:

No.

All enum types are based on integral types. You cannot assign a type to a specific enum member.

See Enum Class on MSDN:

An enumeration is a set of named constants whose underlying type is any integral type. If no underlying type is explicitly declared, Int32 is used. Enum is the base class for all enumerations in the .NET Framework.


You can use attributes to give extra meta data to the members, but you will need to use reflection in order to make use of such attributes.

However, from what you describe, you probably need a custom class that mirrors what you have in the database.

public class CarPart
{
    public string Color { get; set; }
    public int Speed { get; set; }
}
网友答案:

You can create a custom attribute, assignable to members that will have a type property. Included how to access it.

[AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]
public class FieldTypeAttribute : Attribute
{
    public FieldTypeAttribute(Type type)
    {
        Type = type;
    }
    public Type Type { get; set; }

}

public static class FieldTypeInfo<TEnum> where TEnum : struct
{
    public static readonly IDictionary<TEnum, FieldTypeAttribute> Types;

    static FieldTypeInfo()
    {
        var enumTypes = from e in Enum.GetValues(typeof (TEnum)).Cast<TEnum>()
            join m in typeof (TEnum).GetFields(BindingFlags.Public | BindingFlags.Static)
                on e.ToString() equals m.Name
            let i = m.GetCustomAttributes().OfType<FieldTypeAttribute>().SingleOrDefault()
            select new {e, i};

        Types = enumTypes.ToDictionary(es => es.e, es => es.i);
    }
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: