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

Chr*_*uer 2 c# inheritance interface

我有一个继承树,看起来像这样:

Foo并且Bar都有一个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;}
}
Run Code Online (Sandbox Code Playgroud)

Evk*_*Evk 5

泛型可以在这里提供帮助.首先你定义这样的接口:

public interface IMyInterface<out T> where T : BaseId {
    T Id { get; }
}
Run Code Online (Sandbox Code Playgroud)

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

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

public class Bar : IMyInterface<BarId> {
    public BarId Id { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

实现你的目标使用BarId,并FooId在特定的类.

IMyInterface<BaseId>如果你遇到不确切的id类型,这两个类也都是可转换的:

Foo foo = new Foo();
// works fine
var asId = (IMyInterface<BaseId>)foo;
Run Code Online (Sandbox Code Playgroud)