首页 > 解决方案 > 将泛型类型约束定义为与实现相同的类型

问题描述

我想知道是否可以强制对接口或抽象类泛型类型的约束与专门为其实现它的具体类相同。

假设我们想检查某个实体对任务的适应性,并使其在熟练程度方面与其他实体相媲美

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);
        }

那么有没有一种通用的方法来制作某种类或接口来强制它的子类只实现自己的类型与自己的类型比较?像这样,我们只能将人与人进行比较,鱼与鱼进行比较,而没有明确指定可比较实体的类型?

标签: c#.netclassgenericsinterface

解决方案


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。但是,这将允许将继承自的类FishFish.

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);

推荐阅读