协方差和逆变性匿名类型

时间:2012-03-17 01:19:57

标签: c# .net c#-4.0 .net-4.0

我在C#中读到,covariance and contravariance为数组类型,委托类型和泛型类型参数启用隐式引用转换。

我想知道我可以使用匿名类型的协方差和逆变(它们是直接从对象派生的类类型)以及它将如何工作?

1 个答案:

答案 0 :(得分:7)

  

我可以使用通用接口和代表与匿名类型的协方差和逆变吗?

是。匿名类型是引用类型;方差仅适用于引用类型。

  

如何?

界面协方差:

var sequenceOfAnonymous = from c in customers select new {c.Name, c.Age};
var sequenceOfObject = (IEnumerable<object>)sequenceOfAnonymous;

数组协方差:

var arrayOfAnonymous = sequenceOfAnonymous.ToArray();
var arrayOfObject = (object[]) arrayOfAnonymous;

要演示委托协方差,您需要使用泛型类型推理技巧:

static Func<R> MakeFunc(Func<R> f) { return f; }
...
var funcOfAnonymous = MakeFunc( ()=>new { X = 123 } );
var funcOfObject = (Func<object>)funcOfAnonymous;

界面逆变需要一个稍微不同的技巧:逐个示例:

interface IFrobber<in T> { void Frob(T t); }
class Frobber<T> : IFrobber<T> 
{ 
    public void Frob(T t) { Console.WriteLine(t); }
}
...
static IFrobber<T> FrobByExample<T>(IFrobber<T> frobber, T example) 
{ return frobber; }
...
var frobberOfObject = new Frobber<object>();
var frobberOfAnonymous = FrobByExample(frobberOfObject, new { X = 0 });

同样代表逆权:

static Action<A> ActionByExample<A>(Action<A> action, A example) 
{ return action; }
...
var actionOfObject = (Action<object>) x => { Console.WriteLine(x); }
var actionOfAnonymous = ActionByExample(actionOfObject, new { X = 0 } );

有意义吗?