具有相同的接口列表界面 [英] Interface with List of same interface

查看:144
本文介绍了具有相同的接口列表界面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下接口:

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

和这个类

public class Holder<T> where T : IObject {
private T myItem;
public void ChangeItemList(T item){
myItem.List = item.List;
}

但是编译器不喜欢ChangeItemList方法,并在此行:

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

myItem.List = item.List;

给我这个错误:

gives me this error:

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

为什么我不能做到这一点,什么是对于这种情况好的解决办法? 谢谢

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

推荐答案

我不知道你想达到什么,但下面的编译和运行没有异常:

I am not sure what you want to achieve but the following compiles and runs without exceptions:

class Program
{
    static void Main(string[] args)
    {
        var holder = new Holder<IObject>();
        holder.MyItem = new Object { List = new List<IObject>() };
        holder.ChangeItemList(new Object { List = new List<IObject>() });
    }
}

public class Object : IObject
{
    public List<IObject> List { get; set; }
}

public interface IObject
{
    List<IObject> List { get; set; }
}

public class Holder<T> where T : IObject
{
    public T MyItem { get; set; }

    public void ChangeItemList(T item)
    {
        MyItem.List = item.List;
    }
}

这篇关于具有相同的接口列表界面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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