从泛型类型继承为接口

时间:2014-02-07 14:50:20

标签: c# generics inheritance

我正在尝试做类似的事情:

public interface IView<T> : T where T : class 
{ 
    T SomeParam {get;} 
}

这样我以后就可以了

public class SomeView : IView<ISomeView> 
{
}

是否可以通过这种方式使用泛型来指定继承,或者我必须在定义类时明确指定两个接口并执行:

public interface IView<T> 
{ 
    T SomeParam {get;} 
}
public class SomeView : IView<ISomeView>, ISomeView 
{
}

2 个答案:

答案 0 :(得分:1)

这是不可能的,但使用conversion operators可以实现 的目标。您尝试做的似乎是可以将IView<T>作为其包含的T对象传递。您可以编写这样的基类:

public abstract class ViewBase<T> {
    public abstract T SomeParam { get; }

    public static implicit operator T(ViewBase<T> view) {
        return view.SomeParam;
    }
}

然后,如果你定义一个类:

public class SomeView : ViewBase<ISomeView> { }

可以在预期ISomeView的任何地方接受:

ISomeView view = new SomeView();

答案 1 :(得分:0)

简短回答:这是不可能的。见post

接口无法从class派生。但是没有什么能阻止你这样做:

public interface ISomeView
{
}

public interface IView<out T> where T:class 
{
    T SomeParam { get; }
}

public class SomeView:IView<ISomeView>
{
    public ISomeView SomeParam { get; set; }
}    

编辑:

如果您不想在每次需要实施时实施T SomeParam { get; },这是否有效?

public interface ISomeView
{
}

public abstract class BaseView<T> where T : class
{
    public T SomeParam { get; set; }
}

public class SomeView : BaseView<ISomeView>{
}

在这两种情况下都可行:

public class main
{
    public class OneOfThoseView : ISomeView
    {
    }

    public main()
    {
        OneOfThoseView oneOfThose = new OneOfThoseView();
        SomeView x = new SomeView();
        x.SomeParam = oneOfThose;
    }

}

编辑2: 不完全是你想要做的,但这会强制你的SomeView类返回BaseView<SomeView>

public interface ISomeView
{
}

public abstract class BaseView<T> where T : BaseView<T>
{
    public T SomeParam { get; set; }
}

public class SomeView : BaseView<SomeView>
{
}

现在只有这个可行。

public main()
{
    SomeView y= new SomeView ();
    SomeView x = new SomeView();
    x.SomeParam = y;
}