简体   繁体   中英

c# “Enum” on method and “enum” parameter

This is a difficult question to google!

I have an extension method that takes "Enum" as a parameter.

    public static T GetEntry<T>(this Dictionary<Enum, string> dictionary, Enum key)
    {
        string val;
        if (dictionary.TryGetValue(key, out val))
        {
            return (T)Convert.ChangeType(val, typeof(T));               
        }
        return default(T);
    }

but when I try to use it with a declared enum the compiler can't find the extension method

Dictionary<CmdAttr, String> Attributes;
cmd.CommandText.Attributes.GetEntry<double>(CommandText.CmdAttr.X);

Any idea how to make this work other than to declare the dictionary as

Dictionary<Enum, String> Attributes

which works but kind of defeats the point in having a declared enum?

Many Thanks

You can't do it exactly like you want to, because individual enums are not subclasses of Enum . But although this code isn't as pretty as you'd like, it's hardly ugly, and it works as you'd like:

// MyTestEnum.cs

enum MyTestEnum
{
    First,
    Second,
    Third
}

// Extensions.cs

static class Extensions
{
    public static TResult GetEntry<TEnum, TResult>(this Dictionary<TEnum, string> dictionary, TEnum key)
    {
        string value;
        if (dictionary.TryGetValue(key, out value))
        {
            return (TResult)Convert.ChangeType(value, typeof(TResult));
        }
        return default(TResult);
    }
}

// most likely Program.cs

void Main()
{
    Dictionary<MyTestEnum, string> attributes = new Dictionary<MyTestEnum, string>();
    attributes.Add(MyTestEnum.First, "1.23");

    // *** here's the actual call to the extension method ***
    var result = attributes.GetEntry<MyTestEnum, double>(MyTestEnum.First);

    Console.WriteLine(result);
}

What you would like to do is (the following is not valid C# code):

public static T GetEntry<T,U>(this Dictionary<U, string> dictionary, U key) where U : Enum
{
    // your code
}

This will not compile (Constraint cannot be special class 'Enum'). So you have to look for alternatives. There are some good answers to this question. The most easy way would be to use where U : struct, IConvertible

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