小编Seb*_*gor的帖子

对类型约束的反思

在类和方法定义中,可以添加类型约束where T : IFoo.

是否有可能用System.Type或反映这些约束MethodInfo?到目前为止我还没有找到任何东西; 任何帮助将不胜感激.

c# types constraints

18
推荐指数
1
解决办法
2345
查看次数

c#4.0:int一个真正的对象子类型?协方差,可数和值类型

我想知道为什么IEnumerable<int>不能分配到IEnumerable<object>.毕竟IEnumerable是支持协方差的少数接口之一......

  • 子类型关系和协方差的东西适用于引用类型
  • int 似乎是一个适当的亚型 object

两种功能的组合不起作用......

class A
{
}

class B : A
{
}

class Program
{
    static void Main(string[] args)
    {
        bool b;
        b = typeof(IEnumerable<A>).IsAssignableFrom(typeof(List<B>));
        Console.WriteLine("ienumerable of ref types is covariant: " + b); //true

        b = typeof(IEnumerable<object>).IsAssignableFrom(typeof(List<int>));
        Console.WriteLine("ienumerable of value tpyes is covariant: " + b); //false

        b = typeof(object).IsAssignableFrom(typeof(int));
        Console.WriteLine("int is a subtype of object: " + b); //true
    }
}
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助!塞巴斯蒂安

c# ienumerable covariance value-type

9
推荐指数
3
解决办法
1298
查看次数

标签 统计

c# ×2

constraints ×1

covariance ×1

ienumerable ×1

types ×1

value-type ×1