【发布时间】:2012-02-01 00:52:52
【问题描述】:
假设您有以下通用类层次结构:
public abstract class GenericBase<T>
{
T SomeProperty{ get; set; }
}
public class Foo<T>
{
T SomeProperty{ get; set; }
}
public abstract class GenericChild<T> : GenericBase<T>
{
// ...
public bool DoSomething(Foo<T> foo)
{
// This is invalid:
return SomeProperty == foo.SomeProperty;
}
}
DoSomething 方法中的相等性检查无法编译。它会产生以下错误:
Operator '==' cannot be applied to operands of type 'T' and 'T'
如果相关,这些类位于单独的文件中。允许这种平等比较的最佳解决方法是什么?在 C# 中是否有某种模式或某些东西允许这样做?
更新:
一些答案建议使用:
where T : SomeClass
不幸的是,T 通常是一个原始类型。
【问题讨论】:
标签: c# oop generics inheritance