通用抽象类

巴拉尔

我有以下代码很好......

namespace GenericAbstract
{
    public interface INotifModel
    {
        string Data { get; set; }
    }

    public interface INotif<T> where T: INotifModel
    {
       T Model { get; set; }
    }

    public interface INotifProcessor<in T> where T : INotif<INotifModel>
    {
        void Yell(T notif);
    }

    public class HelloWorldModel : INotifModel
    {
        public string Data { get; set; }

        public HelloWorldModel()
        {
            Data = "Hello world!";
        }
    }

    public class HelloWorldNotif : INotif<HelloWorldModel>
    {
        public HelloWorldModel Model { get; set; }

        public HelloWorldNotif()
        {
            Model = new HelloWorldModel();
        }
    }

    public class HelloWorldProcessor<T> : INotifProcessor<T> where T : INotif<INotifModel>
    {
        public void Yell(T notif)
        {
            throw new NotImplementedException();
        }
    }
}

如您所见,有 3 个接口,并且每个接口都已实现。

但是,我希望处理器是这​​样实现的:

public class HelloWorldProcessor : INotifProcessor<HelloWorldNotif<HelloWorldModel>>
{
    public void Yell(HelloWorldNotif<HelloWorldModel> notif)
    {
        throw new NotImplementedException();
    }
}

但我收到以下错误:

非泛型类型“HelloWorldNotif”不能与类型参数一起使用

我希望 HelloWorldProcessorINotifProcessor仅实现HelloWorldNotif...

无法弄清楚我做错了什么..

朱哈尔

为此,您首先必须使INotif<T>协变。这意味着该Model属性只能为接口读取(它仍然可以set在实现中具有公共)。然后要修复您的直接错误,您不要在<HelloWorldModel>之后,HelloWorldNotif因为它已经是INotif<HelloWorldModel>

public interface INotifModel
{
    string Data { get; set; }
}

public interface INotif<out T> where T : INotifModel
{
    T Model { get; }
}

public interface INotifProcessor<in T> where T : INotif<INotifModel>
{
    void Yell(T notif);
}

public class HelloWorldModel : INotifModel
{
    public string Data { get; set; }

    public HelloWorldModel()
    {
        Data = "Hello world!";
    }
}

public class HelloWorldNotif : INotif<HelloWorldModel>
{
    public HelloWorldModel Model { get; set; }

    public HelloWorldNotif()
    {
        Model = new HelloWorldModel();
    }
}

public class HelloWorldProcessor<T> : INotifProcessor<T> where T : INotif<INotifModel>
{
    public void Yell(T notif)
    {
        throw new NotImplementedException();
    }
}

public class HelloWorldProcessor : INotifProcessor<HelloWorldNotif>
{
    public void Yell(HelloWorldNotif notif)
    {
        throw new NotImplementedException();
    }
}

然后我想你的实现会是这样的

Console.WriteLine(notif.Model.Data);

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章