简体   繁体   English

从 IEnumerable 转换的 C#<T> 到 T

[英]C# cast from IEnumerable<T> to T

Can anyone explain that :谁能解释一下:

  • compile OK编译好
  • run-time KO运行时KO

I already checked source code for IEnumerable<> & IEnumerable and found nothing FYI this doesn't work with List我已经检查了 IEnumerable<> 和 IEnumerable 的源代码,但没有发现这不适用于 List

class Program
{
    public class Person
    {
        public long Age { get; set; }
    }

    static void Main(string[] args)
    {
        IEnumerable<Person> list = new List<Person>();
        ((Person)list).Age = 5;
    }
}

There isn't a check at compile time for interface cast to class.在编译时没有检查接口转换为类。

As you can see you can even compile that:如您所见,您甚至可以编译:

class Program
{
    static void Main(string[] args)
    {
        IPizza<Pasta> ao = new Pizza<Pasta>();
        ((Pasta)ao).MyProperty = 10;
    }
}

public interface IPizza<T>
{

}

public class Pizza<T> : IPizza<T>
{

}

public class Pasta
{
    public int MyProperty { get; set; }
}

Interface casted to class will be evaluated in runtime.转换为类的接口将在运行时进行评估。

Infact, if you use as type Pizza<Pasta> instead of IPizza<Pasta> it will give you a compile error:事实上,如果你使用Pizza<Pasta>而不是IPizza<Pasta>作为类型,它会给你一个编译错误:

class Program
{
    static void Main(string[] args)
    {
        Pizza<Pasta> ao = new Pizza<Pasta>();
        ((Pasta)ao).MyProperty = 10;
    }
}
public interface IPizza<T>
{

}

public class Pizza<T> : IPizza<T>
{

}

public class Pasta
{
    public int MyProperty { get; set; }
}

I tried something not too useful but "correct" for both C# compiler & runtime我为 C# 编译器和运行时尝试了一些不太有用但“正确”的东西

I got my answer我得到了答案

    public class Person
    {
        public long Age { get; set; }
    }

    static void Main(string[] args)
    {
        IEnumerable<Person> list;
        list = new Father();
        ((Father)list).Age = 5;
    }

    public class Father : Person, IEnumerable<Person>
    {
        public IEnumerator<Person> GetEnumerator()
        {
            throw new NotImplementedException();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            throw new NotImplementedException();
        }
    }
}

Example例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM