Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/330.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何将泛型类型向下传递给静态方法_C# - Fatal编程技术网

C# 如何将泛型类型向下传递给静态方法

C# 如何将泛型类型向下传递给静态方法,c#,C#,我有一个通用方法,它将返回从枚举填充的选择列表 public static IEnumerable<SelectListItem> GetGenericEnumSelectList<T>() { return (Enum.GetValues(typeof(T)).Cast<int>().Select(e => new SelectListItem() { Text = EnumExtensions.GetEnumDescription((Pro

我有一个通用方法,它将返回从枚举填充的选择列表

public static IEnumerable<SelectListItem> GetGenericEnumSelectList<T>()
{
     return (Enum.GetValues(typeof(T)).Cast<int>().Select(e => new SelectListItem() { Text = EnumExtensions.GetEnumDescription((ProductsEnum)e) , Value = e.ToString() })).ToList();
}
编辑

GetEnumDescription
的签名为

public static string GetEnumDescription(Enum value)
{

///

}

不幸的是,枚举没有通用约束——至少以前没有。因此,以下是不可能的:

void SoSomething<T>(T myEnum) where T: Enum { }
转换为
Enum
时可感知Bw。否则会出现以下错误:

无法将类型
int
转换为
System.Enum


不幸的是,枚举没有通用约束——至少以前没有。因此,以下是不可能的:

void SoSomething<T>(T myEnum) where T: Enum { }
转换为
Enum
时可感知Bw。否则会出现以下错误:

无法将类型
int
转换为
System.Enum



GetEnumDescription
的签名是什么?我打赌它将包含
Enum
作为第一个参数,而不是实际的Enum类型。因此,根本不需要强制转换到特定类型。您可以使用泛型类型进行强制转换,就像任何其他类型
(T)e
@Rafal一样,它假定enum有泛型约束。在这一点上,e是一个int,我得到参数类型“T”不能分配给参数类型“System.Enum”。如果签名需要
Enum
,为什么不直接强制转换到
Enum
?什么是
GetEnumDescription
的签名?我打赌它将包含
Enum
作为第一个参数,而不是实际的Enum类型。因此,根本不需要强制转换到特定类型。您可以使用泛型类型进行强制转换,就像任何其他类型
(T)e
@Rafal一样,它假定enum有泛型约束。在这一点上,e是一个int,我得到“参数类型'T'不可分配给参数类型'System.Enum'如果您的签名仍然需要
Enum
,为什么不直接强制转换为
Enum
?无法将类型'int'转换为'System'Enum'@JsonStatham强制转换为
对象,如我的更新中所示。这在现在的文本中起作用,但是,该值不再是整数,而是文本的副本文本的副本?什么
Enum.GetValues
只返回数字,不返回文本。而
(Enum)e
也不会,那么您指的是哪个文本?我的意思是“Value=e.ToString”用于返回Enum的int值,所以是0,1或2。现在它返回枚举文本“红、黄、绿”,无法将类型“int”转换为“System'enum”@JsonStatham Cast to
object
,正如我在更新中看到的那样。这对现在的文本有效,但是值不再是整数,而是文本副本?什么
Enum.GetValues
只返回数字,不返回文本。而
(Enum)e
也不会,那么您指的是哪个文本?我的意思是“Value=e.ToString”用于返回Enum的int值,所以是0,1或2。现在它返回枚举文本“红、黄、绿”
void SoSomething<T>(T myEnum) where T: struct, IConvertible{ }
return (Enum.GetValues(typeof(T)).Cast<Enum>().Select(e => new SelectListItem { 
    Text = EnumExtensions.GetEnumDescription(e), 
    Value = Convert.ToInt32(e).ToString() 
})).ToList();