首页 新闻 会员 周边

求助一个c#中ICollection接口的问题

0
悬赏园豆:10 [已解决问题] 解决于 2014-12-12 11:35
class Program
    {
        static void Main(string[] args)
        {
            A a = new A();
            a.Col = new List<B>();
            B b = new B();
            b.ID = 1;
            B b2 = new B();
            b2.ID = 2;
            a.Col.Add(b);
            a.Col.Add(b2);

            ICollection<IB> col = a.GetCol();
        }
    }

    public class A
    {
        public ICollection<B> Col { get; set; }

        public ICollection<IB> GetCol()
        {
            return this.Col as ICollection<IB>;
        }
    }

    public class B:IB
    {
        public int ID { get; set; }
    }

    public interface IB
    {
        int ID { get; set; }
    }

 运行后,col为什么会是null

c#
问题补充:

而返回IEnumerable<IB>就有值

cmuler的主页 cmuler | 初学一级 | 园豆:49
提问于:2014-12-12 10:02
< >
分享
最佳答案
0

两个知识点:

1、 as关键字转换不成功返回null;

2、逆变和协变。ICollection<T> 和 IEnumerable<out T> ,,,关键字:out

收获园豆:10
幻天芒 | 高人七级 |园豆:37175 | 2014-12-12 11:18
其他回答(2)
0

而返回IEnumerable<IB>就有值,你这句话说错了吧。返回IEnumerable<IB>没有值啊。你怎么看出ICollection<IB>有值得啊。ICollection<B> Col这个有值啊。也就是你当前的this.col,然后你把this.col转换为IEnumerable<IB>。也就是你把ICollection<B>类型转化为IEnumerable<IB>,是不能转换的,你可以取出里面的对象去转换,但是你连集合、集合类型、T 类型一块转换是不行的啊。比如代码:

 class Program
    {
        static void Main(string[] args)
        {
            A a = new A();
            a.Col = new List<B>();
            B b = new B();
            b.ID = 1;
            B b2 = new B();
            b2.ID = 2;
            a.Col.Add(b);
            a.Col.Add(b2);

            ICollection<B> col = a.GetCol();
            foreach (B item in col)
            {
                IB ib = item as IB;
            }
        }
    }

    public class A
    {
        public ICollection<B> Col { get; set; }

        public ICollection<B> GetCol()
        {
            return this.Col;
        }
    }

    public class B : IB
    {
        public int ID { get; set; }
    }

    public interface IB
    {
        int ID { get; set; }
    }
Mr.Brian | 园豆:1518 (小虾三级) | 2014-12-12 10:41
0

public ICollection<IB> GetCol() {

return this.Col.Cast<IB>().ToArray();

}

Yu | 园豆:12980 (专家六级) | 2014-12-12 11:35
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册