簡體   English   中英

解析具有通用接口子類型的類型

[英]Resolving a type with generic interface subtype

誰能告訴我為什么這個評估返回 false:

using System;
                    
public class Program
{
    public static void Main()
    {
        var a = new Type();
        Console.WriteLine(a is IType<ISubType>); //false
    }
}

public class Type : IType<SubType>
{
}
public interface IType<T>
{
}
    
public class SubType : ISubType
{
}
public interface ISubType
{
}

.NET 小提琴

假設SubType有其自己的獨立於ISubType的行為。 由於TypeSubType有某種關系,它可以依賴SubType的這種獨立行為。

例如,

public class SubType : ISubType
{
    public void Print()
    {
        System.Console.WriteLine("Hello!");
    }
}

var test1 = new List<SubType>
{
    new SubType()
};
test1.First().Print(); //OK

var test2 = new List<ISubType>
{
    new SubType()
};
test2.First().Print(); //Error CS1061: 'ISubType' does not contain a definition for 'Print' and no accessible extension method 'Print' …

@Jeroen Mostert 對這個問題有很好的評論。 繼續該推理,如果您希望評估返回true 請像這樣聲明你的接口:

public interface IType<out T>
{

}

您可以使用ICollection<Animal>作為ICollection<Giraffe>從動物集合中獲取長頸鹿

https://do.netfiddle.net/bnUG1S

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM