有什么办法让方法返回一个方法中的任何一个泛型类型?例如,我有以下几点:C#中的可变通用返回类型#
public static T ParseAttributeValue<T>(this XElement element, string attribute)
{
if(typeof(T) == typeof(Int32))
{
return Int32.Parse(element.Attribute(attribute).Value);
}
if(typeof(T) == typeof(Double))
{
return Double.Parse(element.Attribute(attribute).Value);
}
if(typeof(T) == typeof(String))
{
return element.Attribute(attribute).Value;
}
if(typeof(T) == typeof(ItemLookupType))
{
return Enum.Parse(typeof(T), element.Attribute(attribute).Value);
}
}
(这仅仅是一个非常快速的样机,我知道,任何产品代码将需要在空支票等显著更彻底...)
但编译器不喜欢它,抱怨Int32
不能隐式转换为T
(它不适用于强制转换)。我能理解这一点。在编译时,它无法知道什么是T
,但我正在事先检查它。无论如何,我可以做这项工作吗?
否,则''只是类型参数。您使用不带括号的类型。 –
Femaref
2012-07-19 18:46:57
@Femaref - 好点。问题被撤销。 – 2012-07-19 18:50:30
如果将该值存储为Object,则可以对其进行转换。也可以将该功能键入为动态,这可能会帮助您在没有投射的情况下进行操作。 – MrWednesday 2012-07-19 18:51:30