![](/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.