c# - 将泛型类型约束定义为与实现相同的类型
问题描述
我想知道是否可以强制对接口或抽象类泛型类型的约束与专门为其实现它的具体类相同。
假设我们想检查某个实体对任务的适应性,并使其在熟练程度方面与其他实体相媲美
abstract class Entity
{
public abstract int Fitness(); //Bigger the number - more fit the entity is
public int MoreFitThan(Entity other)
{
return Fitness().CompareTo(other.Fitness());
}
}
class Fish : Entity
{
public int swimSpeed { get; set; }
public override int Fitness()
{
return swimSpeed;
}
}
class Human : Entity
{
public int testPoints { get; set; }
public override int Fitness()
{
return testPoints;
}
}
但是现在我们可以将鱼的速度与人类的测试通过能力进行比较,这没有任何意义。
static void Main()
{
Human human = new Human() {testPoints = 10};
Fish fish = new Fish() { swimSpeed = 20 };
fish.MoreFitThan(human);
}
那么有没有一种通用的方法来制作某种类或接口来强制它的子类只实现自己的类型与自己的类型比较?像这样,我们只能将人与人进行比较,鱼与鱼进行比较,而没有明确指定可比较实体的类型?
解决方案
MoreFitThan
您可以通过以下方式使用泛型强制传递给的类型与继承类匹配。
abstract class Entity<T> where T : Entity<T>
{
public abstract int Fitness(); //Bigger the number - more fit the entity is
public int MoreFitThan(T other)
{
return Fitness().CompareTo(other.Fitness());
}
}
class Fish : Entity<Fish>
{
public int swimSpeed { get; set; }
public override int Fitness()
{
return swimSpeed;
}
}
class Human : Entity<Human>
{
public int testPoints { get; set; }
public override int Fitness()
{
return testPoints;
}
}
那么以下将是编译错误
Human human = new Human() {testPoints = 10};
Fish fish = new Fish() { swimSpeed = 20 };
fish.MoreFitThan(human);
因为Human
不是一个Fish
。但是,这将允许将继承自的类Fish
与Fish
.
class Trout : Fish
{
public int size { get; set; }
public override int Fitness()
{
return size;
}
}
以下是有效的,因为 aTrout
是 a Fish
。
Trout trout = new Trout() {size = 10};
Fish fish = new Fish() { swimSpeed = 20 };
fish.MoreFitThan(trout);
推荐阅读
- c - 代码显示分段错误,但我无法找到它
- typescript - 单击复选框时如何禁用div
- linux - 删除名称为 '\' 的文件
- windows - CMD 中的全局命令在目录及其所有子目录中执行
- git - 如果根目录中的文件与特定的命名约定不匹配,有没有办法让 git 忽略文件?
- javascript - 如何在javascript中选择元素
- sql - 使用 group by 在另一个表中添加行存在标志
- javascript - 排序jquery数据表的问题
- css - 如何以不规则的方式对齐块
- xamarin.forms - Xamarin ios Rejection-由于Xamarin.Forms.Platform.iOS中的UIWebview。这是什么包?