在泛型方法中返回特定类型 [英] Return specific type in generic method
问题描述
我编写了以下方法:
public T CreatePackage<T>() where T : new()
{
var package = new T();
if (typeof(ComponentInformationPackage) == typeof(T))
{
var compInfoPackage = package as ComponentInformationPackage;
// ...
return compInfoPackage;
}
throw new System.NotImplementedException();
}
我检查 T 是什么类型,并据此处理变量 Package .当我想返回它时,出现编译器错误.
I check what type T is and according to this I treat my variable Package. When I want to return it I get an compiler error.
类型 ComponentInformationPackage 不能隐式转换为T"
"The type ComponentInformationPackage cannot be implicitly converted to T"
我该如何解决这个问题?
How can I solve this problem?
推荐答案
首先:在强制转换无效的情况下,安全的强制转换有效
First: Where a cast doesn't work, a safe cast does work:
return CompInfoPackage as T;
...只要在T
上存在class
约束:
...provided there's a class
constraint on T
:
public static T CreatePackage<T>() where T : class, new() { ... }
第二:给出以下代码:
var package = new T();
if (typeof(ComponentInformationPackage) == typeof(T))
{
var compInfoPackage = package as ComponentInformationPackage;
// ...
return (T)compInfoPackage;
}
...您已经有了对新对象的引用package
.由于它的类型为T
,因此编译器已经喜欢将其作为返回类型.为什么不退还?
...you already have the reference package
to the new object. Since it's of type T
, the compiler already likes it as a return type. Why not return that?
var package = new T();
if (typeof(ComponentInformationPackage) == typeof(T))
{
var compInfoPackage = package as ComponentInformationPackage;
// ...
return package; // Same object as compInfoPackage
}
这篇关于在泛型方法中返回特定类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!