开发者

How to detect an anonymous object with .NET Reflection? [duplicate]

This question already h开发者_开发技巧as answers here: Closed 12 years ago.

Possible Duplicates:

How To Test if a Type is Anonymous?

Anonymous Types - Are there any distingushing characteristics?

Is there a way to detect if a Type object refers to an anonymous object?

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


No, there is no way because anonymous types are just a compile time artifact, at runtime they are just regular types emitted by the compiler. As they are compiler generated those types are marked with the CompilerGeneratedAttribute which could be used to determine if this is the case.

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

Of course that will return true also for types that were decorated with this attribute so it's not 100% guarantee that it is an anonymous type

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜