【发布时间】:2016-12-09 10:39:23
【问题描述】:
如何创建一个接受一种泛型类型并返回另一种泛型类型的 C# 泛型方法?我如何获得 T 的实际类型,以便我可以将我的新类型作为通用 T 类型返回。
基本上,我想实现类似这个示例代码的东西,其中if/else 逻辑在类型之间转换。如果有更好的方法来做同样的事情,比如使用 Func,请告诉我。任何帮助,将不胜感激。谢谢。
编辑: 好的,这几乎正是我想要做的。 (只是类型不同)我不认为“Convert.ChangeType”会起作用,因为我使用的是自定义类型。
public interface ICustomType{}
public struct TypeA : ICustomType {}
public struct TypeB : ICustomType {}
public struct TypeC : ICustomType {}
public static T Convert<T>(ICustomType input) where T : ICustomType
{
var output = default(T);
if (output is TypeA)
{
if (input is TypeA)
{
output = input;
}
else if (input is TypeB)
{
output = CustomTypeB_ToTypeA_Converter(input);
}
else if (input is TypeC)
{
output = CustomTypeC_ToTypeA_Converter(input);
}
}
else if (output is TypeB)
{
if (input is TypeA)
{
output = CustomTypeA_ToTypeB_Converter(input);
}
else if (input is TypeB)
{
output = input;
}
else if (input is TypeC)
{
output = CustomTypeC_ToTypeB_Converter(input);
}
}
else if (output is TypeC)
{
// same pattern as above
}
return output;
}
可能的用例:
TypeA a = 45;
TypeB result = Convert<TypeB>(a);
【问题讨论】:
-
你能展示你正在尝试做什么的例子吗?...编译器也不能推断出通用返回类型。如果泛型仅用于返回,则必须在调用方法时指定它。
-
您可能对Convert.ChangeType感兴趣
-
.Net中还有很多Convert方法,用
Convert. -
我会提供更多关于您的实际目标的背景信息。我不确定泛型是否适合您的情况....