【问题标题】:Inherit from generic type as interface从泛型类型继承为接口
【发布时间】:2014-03-05 00:56:23
【问题描述】:

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

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 
{
}

【问题讨论】:

标签: c# generics inheritance


【解决方案1】:

这是不可能的,但您的目标可能可以通过conversion operators 实现。似乎您正在尝试做的是可以将IView&lt;T&gt; 作为它包含的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();

【讨论】:

    【解决方案2】:

    简答:不可能。看到这个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&lt;SomeView&gt;

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

    【讨论】:

    • 正如我所说,这是我试图避免的事情。我宁愿定义越少越好。
    • 你想要一个基础抽象类?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-25
    • 1970-01-01
    • 1970-01-01
    • 2020-03-02
    • 2023-03-22
    • 2020-12-01
    • 1970-01-01
    相关资源
    最近更新 更多