简体   繁体   中英

C# Enum for datatypes

Is there any enum in c# which holds c# datatypes. So that I can define a property in a class which accepts datatype (int,string) from the user.

There is the TypeCode Enumeration in System. Looks like it covers all of the base types.

You can get the TypeCode for any object using Type.GetTypeCode():

TypeCode typeCode = Type.GetTypeCode(anObject.GetType());

Do you simply want to associate an enum value with a string? You might want to use the Description attribute.

public enum MyEnum
{
    [Description("My first value.")]
    FirstValue,
    [Description("My second value.")]
    SecondValue,
    [Description("My third value.")]
    ThirdValue
}

private string GetEnumDescription(Enum value)
{
    FieldInfo fi = value.GetType().GetField(value.ToString());
    DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
    if (attributes.Length > 0)
    {
        return attributes[0].Description;
    }
    else
    {
        return value.ToString();
    }
}

Another possibility for defining a mapping would be to use a Dictionary<int, string> .

Type-type有一个布尔属性“IsPrimitive”希望这可以帮到你。

There is nothing like that in the BCL.

Why do you need it?

Based on your edit sounds like you need generics but I still question why a property would acceptably be an int or a string. Those are really very different things which can only lead to upcasting.

Why do you need that? The property is already a "filter" to what kind of data it can accept.

Have a look at :

Overloading properties in C#

Unfortunately the framework does not have such enum, you will have to create it by hand (as we did as we had the same need as you).

Regards.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM