【问题标题】:How to find out if object is of Anonymous type? [duplicate]如何确定对象是否为匿名类型? [复制]
【发布时间】:2010-06-16 06:41:06
【问题描述】:

可能重复:
Anonymous Types - Are there any distingushing characteristics?

找不到合适的属性。

if(new {a = 2, b= "z"}.GetType()...)

放什么而不是...?

【问题讨论】:

  • 欢迎来到SO,请不要忘记访问stackoverflow.com/faq
  • 据我所知,没有现成的解决方案,在这个问题和stackoverflow.com/questions/315146/… 中提供的所有答案听起来更像是可能停止使用不同/新编译器版本的解决方法。如果有类似 if(new {a = 2, b= "z"}.GetType().IsAnonymousType)

标签: c# anonymous-types


【解决方案1】:

除了以<> 开头并包含AnonymousType 的奇怪名称(在C# 中,如在VB 中它以VB$ 开头),没有太多需要测试的东西。但是,我不会打赌名称测试...

【讨论】:

    【解决方案2】:

    您是否尝试过输出new { a = 2, b = "z" }.GetType() 来获得一个比较值?如果没有,这是我首先要做的。

    var t = new { a = 2, b = "z" }.GetType();
    
    var c = 2; // set a breakpoint on this line, and see what t contains
    

    【讨论】:

      【解决方案3】:

      匿名类将包含名称 AnonymousType,它们不会有命名空间或声明类型。您可以使用它来查看它是否是匿名的。虽然我不确定它有多安全......

      var t = new { a = 2, b = "z" }.GetType();
      bool isAnonymous = t.Namespace == null && t.DeclaringType == null;
      

      【讨论】:

      • Namespace 对于全局类也可以为空,DeclaringType 对于非嵌套类型无论如何都将为空。 -1.
      • @nawfal:好的。这回答了我的“虽然我不确定它有多安全......”:)
      猜你喜欢
      • 2010-12-11
      • 2011-01-29
      • 1970-01-01
      • 1970-01-01
      • 2011-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多