如何在泛型方法中获取类型参数的名称?
How do I get the name of a type argument in a generic method?
我的 class 中有一个通用方法:
public static void populateSoapBody<TEnum>(Object obj, string[] aMessage)
where TEnum : struct, IComparable, IFormattable, IConvertible
然后我用它从字符串数组 aMessage
中填充 class obj
(详见 在我的另一个问题中)...
现在,对于错误记录,我想获取为 TEnum
类型参数传入的类型参数的名称。例如:
private enum DCSSCutomerUpdate_V3
{
...
}
所以,当我这样调用方法时:
Common.populateSoapBody<DCSSCustomerUpdate_V3>(wsSoapBody, aMessage);
在那个方法中,我希望能够将 DCSSCustomerUpdate_V3
作为字符串
I want the name of the actual constant.
obj.ToString()
如果 obj 是枚举类型的盒装实例,则为您提供枚举元素的名称。例如:
class P
{
enum E { ABC }
static void Main()
{
object obj = E.ABC;
Console.WriteLine(obj.ToString()); // ABC
}
}
I want the name of the Enumerated constant that I pass in when calling it. So, defined by TEnum
so when I call the method using Common.populateSoapBody<DCSSCustomerUpdate_V3>(wsSoapBody, aMessage);
I can get the string DCSSCustomerUpdate_V3
这不是一个常量。如果您对事物使用正确的名称,那么您自己和试图帮助您的人都会变得更加轻松。
上面的E.ABC
是一个常量。 E
是 类型 。在您的示例中,TEnum
是一个 类型参数 ,类型 DCSSCustomerUpdate_V3
是一个 类型参数 。
因此您的问题是:
I have a generic method M<T>()
; how do I get the name of the type argument supplied for type parameter T
?
答案是:
void M<T>()
{
Console.WriteLine(typeof(T).Name);
}
要获取 type TEnum
的名称,只需使用:
typeof(TEnum).Name
请注意,这与枚举无关,它不是 "Enumerated constant",所以我认为您在这里也有一些术语错误。
我的 class 中有一个通用方法:
public static void populateSoapBody<TEnum>(Object obj, string[] aMessage)
where TEnum : struct, IComparable, IFormattable, IConvertible
然后我用它从字符串数组 aMessage
中填充 class obj
(详见
现在,对于错误记录,我想获取为 TEnum
类型参数传入的类型参数的名称。例如:
private enum DCSSCutomerUpdate_V3
{
...
}
所以,当我这样调用方法时:
Common.populateSoapBody<DCSSCustomerUpdate_V3>(wsSoapBody, aMessage);
在那个方法中,我希望能够将 DCSSCustomerUpdate_V3
作为字符串
I want the name of the actual constant.
obj.ToString()
如果 obj 是枚举类型的盒装实例,则为您提供枚举元素的名称。例如:
class P
{
enum E { ABC }
static void Main()
{
object obj = E.ABC;
Console.WriteLine(obj.ToString()); // ABC
}
}
I want the name of the Enumerated constant that I pass in when calling it. So, defined by
TEnum
so when I call the method usingCommon.populateSoapBody<DCSSCustomerUpdate_V3>(wsSoapBody, aMessage);
I can get the stringDCSSCustomerUpdate_V3
这不是一个常量。如果您对事物使用正确的名称,那么您自己和试图帮助您的人都会变得更加轻松。
上面的E.ABC
是一个常量。 E
是 类型 。在您的示例中,TEnum
是一个 类型参数 ,类型 DCSSCustomerUpdate_V3
是一个 类型参数 。
因此您的问题是:
I have a generic method
M<T>()
; how do I get the name of the type argument supplied for type parameterT
?
答案是:
void M<T>()
{
Console.WriteLine(typeof(T).Name);
}
要获取 type TEnum
的名称,只需使用:
typeof(TEnum).Name
请注意,这与枚举无关,它不是 "Enumerated constant",所以我认为您在这里也有一些术语错误。