.NET泛型方法问题 [英] .NET Generic Method Question
问题描述
我试图掌握.NET泛型的概念和实际使用他们自己的code,但我依然会碰到的一个问题。
I'm trying to grasp the concept of .NET Generics and actually use them in my own code but I keep running into a problem.
可有人试图向我解释为什么以下安装不能编译?
Can someone try to explain to me why the following setup does not compile?
public class ClassA
{
ClassB b = new ClassB();
public void MethodA<T>(IRepo<T> repo) where T : ITypeEntity
{
b.MethodB(repo);
}
}
public class ClassB
{
IRepo<ITypeEntity> repo;
public void MethodB(IRepo<ITypeEntity> repo)
{
this.repo = repo;
}
}
我收到以下错误:
不能从IRepo&LT转换,'T>为IRepo&LT;'ITypeEntity>
I get the following error:
cannot convert from IRepo<'T> to IRepo<'ITypeEntity>
治法被调用了IRepo&LT;DetailType>目标参数,其中DetailType从ITypeEntity继承
MethodA gets called with a IRepo<'DetailType> object parameter where DetailType inherits from ITypeEntity.
我一直在想,这应该编译为我牛逼约束内治法为类型ITypeEntity的。
I keep thinking that this should compile as I'm constraining T within MethodA to be of type ITypeEntity.
任何想法或意见,将非常有帮助。
Any thoughts or feedback would be extremely helpful.
感谢。
编辑:尼克R有一个伟大的建议,但遗憾的是在我的情况下,我没有做通用的ClassA的选择。 ClassB的可能,但。
Nick R has a great suggestion but unfortunately in my context, I don't have the option of making ClassA Generic. ClassB could be though.
推荐答案
继承使用泛型时不工作一样。由于Smashery指出,即使从类型A的TypeB,与的myType其中继承;类型A>不会从&的myType其中继承;的TypeB>。
Inheritance doesn't work the same when using generics. As Smashery points out, even if TypeA inherits from TypeB, myType<TypeA> doesn't inherit from myType<TypeB>.
因此,你不能让一个呼叫定义为治法的方法;期待与的myType LT( - 的myType LT>乙的TypeB);类型B>,并给它一个 - 的myType其中,类型A>代替。问题的类型必须完全匹配。因此,以下不会编译:
As such, you can't make a call to a method defined as MethodA(myType<TypeB> b) expecting a myType<TypeB> and give it a myType<TypeA> instead. The types in question have to match exactly. Thus, the following won't compile:
myType<TypeA> a; // This should be a myType<TypeB>, even if it contains only TypeA's
public void MethodB(myType<TypeB> b){ /* do stuff */ }
public void Main()
{
MethodB(a);
}
所以,你的情况,你需要传递一个IRepo&LT; ITypeEntity>到方法b,即使它只包含DetailTypes。你需要做两者之间的一些转换。如果你使用的是通用的IList,你可以做到以下几点:
So in your case, you would need to pass in an IRepo<ITypeEntity> to MethodB, even if it only contains DetailTypes. You'd need to do some conversion between the two. If you were using a generic IList, you might do the following:
public void MethodA<T>(IList<T> list) where T : ITypeEntity
{
IList<T> myIList = new List<T>();
foreach(T item in list)
{
myIList.Add(item);
}
b.MethodB(myIList);
}
我希望这是有帮助的。
I hope this is helpful.
这篇关于.NET泛型方法问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!