如何使用.NET Reflection检测匿名对象?

时间:2010-07-19 10:54:00

标签: .net reflection

  

可能重复:
  How To Test if a Type is Anonymous?
  Anonymous Types - Are there any distingushing characteristics?

有没有办法检测Type对象是否引用了匿名对象?

var obj = new { A = "Hello" };
Type x = obj.GetType();
// is there something equivalent to x.IsAnonymous?
Assert.IsTrue(x.IsAnonymous);

1 个答案:

答案 0 :(得分:3)

不,没有办法,因为匿名类型只是一个编译时工件,在运行时它们只是编译器发出的常规类型。由于它们是编译器生成的,因此这些类型标有CompilerGeneratedAttribute,可用于确定是否属于这种情况。

var obj = new { A = "Hello" };
var isAnonTypeCandidate = obj
    .GetType()
    .GetCustomAttributes(typeof(CompilerGeneratedAttribute), true)
    .Count() > 0;

当然,对于使用此属性修饰的类型,也会返回true,因此不能100%保证它是匿名类型