簡體   English   中英

C#“方法”和“枚舉”參數“枚舉”

[英]c# “Enum” on method and “enum” 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);
    }

但是當我嘗試將其與聲明的枚舉一起使用時,編譯器找不到擴展方法

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

除了將字典聲明為以外,如何使這項工作有效的任何想法

Dictionary<Enum, String> Attributes

哪個有效,但是有點違反了聲明一個枚舉的意義?

非常感謝

您無法完全按照自己的意願進行操作,因為單個枚舉不是Enum子類。 但是,盡管這段代碼並不像您想要的那樣漂亮,但它並不難看,並且可以根據您的需要進行工作:

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

您想要做的是(以下無效的C#代碼):

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

這將不會編譯(約束不能是特殊類'Enum')。 因此,您必須尋找替代方案。 這個問題有一些好的答案。 最簡單的方法是使用where U : struct, IConvertible

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM