c#“Enum”方法和“枚举”参数 [英] c# "Enum" on method and "enum" parameter
问题描述
我有一个扩展方法,以枚举为参数。
public static T GetEntry< T>(此字典<枚举,字符串>字典,枚举键)
{
string val;
if(dictionary.TryGetValue(key,out val))
{
return(T)Convert.ChangeType(val,typeof(T));
}
返回默认(T);
}
但是当我尝试使用一个声明的枚举时,编译器不能找到扩展方法
字典< CmdAttr,String>属性;
cmd.CommandText.Attributes.GetEntry< double>(CommandText.CmdAttr.X);
任何想法如何使这项工作除了将该字典声明为
字典<枚举,字符串>属性
哪些工作有点失败,具有一个声明的枚举?
非常感谢
你不能像你想要那样做,因为个人枚举不是枚举
的子类。但是,虽然这段代码并不像你想要的那样漂亮,但它并不难看,它的工作原理如下:
// MyTestEnum.cs
枚举MyTestEnum
{
首先,
第二,
第三
}
// Extensions.cs
static class Extensions
{
public static TResult GetEntry< TEnum,TResult>(此字典< TEnum,string>字典,TEnum键)
{
string value;
if(dictionary.TryGetValue(key,out value))
{
return(TResult)Convert.ChangeType(value,typeof(TResult));
}
return default(TResult);
}
}
//最有可能的Program.cs
void Main()
{
Dictionary< MyTestEnum,串GT; attributes = new Dictionary< MyTestEnum,string>();
attributes.Add(MyTestEnum.First,1.23);
// ***这里是扩展方法的实际调用***
var result = attributes.GetEntry< MyTestEnum,double>(MyTestEnum.First);
Console.WriteLine(result);
}
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);
}
这篇关于c#“Enum”方法和“枚举”参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!