C#实现接口定义的派生类型?

时间:2018-04-30 15:10:26

标签: c# inheritance interface

我有一个继承树,如下所示:

FooBar都有Id,通过特定的Id类定义。 id类本身派生自一个公共基类。

我现在想写一个可以包含FooBar的界面, 但编译器不允许这样做,我必须使用BaseId作为FooBar中的类型,但我想避免这种情况。

public class BaseId
{
    public string Id {get; set;}
}

public class FooId: BaseId
{}

public class BarId: BaseId
{}

public interface MyInterface
{
    public BaseId Id {get; set; }
}

public class Foo: MyInterface
{
    public FooId Id {get; set;}
}

public class Bar: MyInterface
{
    public BarId Id {get; set;}
}

1 个答案:

答案 0 :(得分:5)

泛型可以在这里提供帮助。首先,您定义如下界面:

public interface IMyInterface<out T> where T : BaseId {
    T Id { get; }
}

然后你可以像这样实现它:

public class Foo : IMyInterface<FooId> {
    public FooId Id { get; set; }
}

public class Bar : IMyInterface<BarId> {
    public BarId Id { get; set; }
}

实现在特定课程中使用BarIdFooId的目标。

如果您遇到不确切ID类型的情况,这两个课程也可投递到IMyInterface<BaseId>

Foo foo = new Foo();
// works fine
var asId = (IMyInterface<BaseId>)foo;
相关问题