通用抽象类

时间:2017-04-07 13:09:14

标签: c# generics

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

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

但我收到以下错误:

  

非通用类型&#39; HelloWorldNotif&#39;不能与类型参数一起使用

我希望HelloWorldProcessor仅为INotifProcessor实现HelloWorldNotif ...

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

2 个答案:

答案 0 :(得分:1)

正如其他人已经说过和/或暗示你已经完全指定了HelloWorldNotif。所以翻译一下:

  

我希望HelloWorldProcessor仅为其实现INotifProcessor   HelloWorldNotif

对于C#,我认为你的意思是:

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

答案 1 :(得分:1)

为此,首先必须使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);