C# 泛型 - 从泛型类调用泛型方法
我有以下类,并且尝试从 ExportFileBaseBL 类调用 Compare 方法,但收到错误
无法将类型“Class1”隐式转换为“T”。存在显式转换(是否缺少强制转换?)
public abstract class Class1<T> where T: Class2
{
public abstract Class1<T> Compare(Class1<T> otherObj);
}
public abstract class Class3<T, U> where T: Class1<U>
where U: Class2
{
public T Compare(T obj1, T obj2)
{
if (obj1.Prop1 > obj2.Prop1)
{
return obj1.Compare(obj2); // Compiler Error here
}
else
{
return obj2.Compare(obj1); // Compiler Error here
}
}
}
类型转换不应该是隐式的吗?我错过了什么吗?
I have the following classes and I am trying to call Compare method from ExportFileBaseBL class but I get the error
Cannot implicitly convert type 'Class1' to 'T'. An explicit conversion exists (are you missing a cast?)
public abstract class Class1<T> where T: Class2
{
public abstract Class1<T> Compare(Class1<T> otherObj);
}
public abstract class Class3<T, U> where T: Class1<U>
where U: Class2
{
public T Compare(T obj1, T obj2)
{
if (obj1.Prop1 > obj2.Prop1)
{
return obj1.Compare(obj2); // Compiler Error here
}
else
{
return obj2.Compare(obj1); // Compiler Error here
}
}
}
Shouldn't the type conversion be implicit? Am I missing something?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题在于您的抽象
Compare
方法被定义为接受Class1
类型的参数并返回Class1
的实例,不是比Class1
更具体的类型。但这就是您的Class3.Compare
方法尝试执行的操作:调用T.Compare
并假设输出将是T
,当事实上,您只能确定它是Class1
。为了提供一个更简单、更容易理解的示例,假设我有这个类:
上面的代码做出了一个与您自己类似的错误假设:
parser.Parse
将返回一个int
因为int
派生自object
(就像您的情况一样,T
必须派生自Class1
);事实上,您只能确定它将返回一个对象
。我认为有两种方法可以解决此问题:使
Class1.Compare
成为通用方法:...或放宽
Class3.Compare
的类型特异性方法的返回值:就个人而言,我更喜欢第二个,除非您绝对需要第一个。当复杂性开始像这样增长时,所有这些泛型类型约束都会变得非常混乱,给您带来的负担超出您的预期。
The problem is that your abstract
Compare
method is defined to accept a parameter of typeClass1<T>
and return an instance ofClass1<T>
, not a more specific type thanClass1<T>
. But this is what yourClass3.Compare
method is attempting to do: callT.Compare
and assume the output will be aT
, when in fact you can only be sure it will be aClass1<U>
.To provide a simpler, more comprehensible example, suppose I had this class:
The above code makes a faulty assumption similar to your own: that
parser.Parse
will return anint
just becauseint
derives fromobject
(just as in your case,T
must derive fromClass1<U>
); in fact, you can only be sure it will return anobject
.There are two ways I can see to fix this problem: make
Class1<T>.Compare
a generic method:...or relax the type specificity of your
Class3.Compare
method's return value:Personally, I would prefer the second unless you absolutely need the first. All these generic type constraints can become very messy and burden you more than you expect when the complexity starts to grow like this.
使用您在类级别声明的参数类型调用该方法。
您还需要使 Compare 方法的定义通用:
Call the method with the parameter type you declaring at your class level.
You'll need to make the definition of the Compare method generic as well: