C#接口强制属性是另一个接口?

Jam*_*ght 1 c# inheritance interface

鉴于此代码:

public interface ITagModel { }

public interface ITemplate {
    ITagModel Model { get; set; }
}

public class EmailTag : ITagModel { }

public class EmailTest : ITemplate {
    public EmailTag Model { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我被告知类型EmailTag(内部EmailClass)无法实现属性,Model因为它不是类型ITagModel.

它继承了ITagModel ....所以为什么这不起作用?我能做些什么来完成我正在寻找的东西?

Dus*_*gen 5

C#不支持协变返回.

例如

public class Base { }
public class Derived : Base { }

public class Component
{
    public virtual Base GetComponent()
    {
        return new Base();
    }
}

public class DerviedComponent : Component
{
    public override Dervied GetComponent()
    {
        return new Derived();
    }
}
Run Code Online (Sandbox Code Playgroud)

因此,您需要抽象返回类型并将其约束到您的界面.这样任何实现都需要提供ITagModel.

public interface ITagModel { }

public interface ITemplate<TModel>
    where TModel : ITagModel
{
    TModel Model { get; set; }
}

public class EmailTag : ITagModel { }

public class EmailTest : ITemplate<EmailTag> {
    public EmailTag Model { get; set; }
}
Run Code Online (Sandbox Code Playgroud)