![](/img/trans.png)
[英]Resolving Interface with generic type constraint with Castle Windsor
[英]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
{
}
假設SubType
有其自己的獨立於ISubType
的行為。 由於Type
與SubType
有某種關系,它可以依賴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>
從動物集合中獲取長頸鹿
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.