List <Type>转换为IEnumerable <Interface>,然后转换为List <Interface>为null

如果标题不清楚,请原谅我,但找不到其他方式描述遇到的情况。 在编写类似于以下内容的代码时遇到了一个问题:

using System;
using System.Collections.Generic;
using System.Linq;

public interface IInterfaceReadOnly
{
    int Value {get;}
}

public interface IInterface : IInterfaceReadOnly
{
    new int Value{get; set;}
}

public class Implementation : IInterface {
    public int Value{get; set;}
}

public class Program
{
    public static void Main()
    {
        List<Implementation> implementations = new List<Implementation>();
        IEnumerable<IInterfaceReadOnly> generic = implementations;

        List<IInterfaceReadOnly> listOfGeneric1 = generic as List<IInterfaceReadOnly>;
        List<IInterfaceReadOnly> listOfGeneric2 = generic.ToList();

        // this prints "is null",listOfGeneric1 is null
        if (listOfGeneric1 == null) Console.WriteLine("Is null");
        else Console.WriteLine("Not null");

        // this prints "not null",listOfGeneric2 is converted successfully
        if (listOfGeneric2 == null) Console.WriteLine("Is null");
        else Console.WriteLine("Not null");
    }
}

如注释中所述,使用“ as”运算符的第一个转换返回null,这意味着强制转换失败,而使用ToList()强制转换就可以了。 预先感谢您的任何澄清。

sunxiangmin 回答:List <Type>转换为IEnumerable <Interface>,然后转换为List <Interface>为null

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/3114175.html

大家都在问