与接口类型的通用对象的接口 [英] Interface with generic object of the interface type

查看:139
本文介绍了与接口类型的通用对象的接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下界面:

public interface IObject
{
    double x { get; }
    double y { get; }
    Holder<IObject> Holder { get; set; }
}

此课程

public class Holder<T> where T : IObject 
{
  private List<T> items; 
  public void AddItem(T item){
     items.Add(item);
     item.Holder = this;
}

但是编译器不喜欢AddItem方法并且在这一行:

However the compiler doesn't like the AddItem method and on this line :

item.Holder = this;

给我这个错误:

Cannot convert source type 'Holder<T>' to target type 'Holder<IObject>'

为什么我不能这样做,这个场景有什么好的解决方案?
谢谢

Why can't I do it and what is a good solution for this scenario? thank you

推荐答案

你必须牢记Genrics在C#中的工作方式,编译器创建一个类指定的类型,因此你有错误。

You have to bear in mind the way Genrics works in C#, The compiler create a class of the specified type, and because of that you have the error.

为了解释更多,给出以下示例:

To explain more, given the following example:

public class InterfaceImplementation : IObject
{
}

然后你做的一些事情:

var genericInitialisation = new Holder<InterfaceImplementation>();

编译时编译器将创建一个类 HolderInterfaceImplementation 替换 T 泛型参数的所有准确性。

The compiler at compile time will create a class HolderInterfaceImplementation replacing all accurances of the T generic parameter.

所以在编译之后你将拥有这个类:

so after compilation you will have this class:

public class HolderInterfaceImplementation
{
  private ListInterfaceImplementation items; 
  public void AddItem(InterfaceImplementation item){
     items.Add(item);
     item.Holder = this;
}

item.Holder 将是 HolderIObject 类型,因此编译器报告错误,无法将 HolderInterfaceImplementation 转换为 HolderIObject 这是合乎逻辑的。

And item.Holder would be HolderIObject type, so the compiler report an error about not being able to convert HolderInterfaceImplementation to HolderIObject wich is logical.

在解释理论之后解决方案自然而然就是一个例子:

After explaining the theory the solution comes naturaly and here is an example:

    public interface IObject<T> where T : IObject<T>
    {
      double x { get; }
      double y { get; }
      Holder<T> Holder { get; set; }
    }


    public class Holder<T> where T : IObject<T>
    {
      public Holder()
      {
        items = new List<T>();
      }
      private List<T> items;
      public void AddItem(T item)
      {
        items.Add(item);
        item.Holder = this;
      }
    }

    public class Implementation : IObject<Implementation>
    {

      public double x
      {
        get { return 0; }
      }

      public double y
      {
        get { return 0; }
      }

      public Holder<Implementation> Holder
      {
        get;
        set;
      }
    }
    static void Main(string[] args)
    {
      var t = new Holder<Implementation>();
      t.AddItem(new Implementation());
      Console.ReadKey();
    }

这篇关于与接口类型的通用对象的接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆