代码之家  ›  专栏  ›  技术社区  ›  iamserious

如果我不知道c#中的结构,如何访问Object的内容?

c#
  •  2
  • iamserious  · 技术社区  · 15 年前

    我有一个对象,直到运行时才知道它的结构。那么,有没有办法从对象中访问数据呢?

    谢谢。

    3 回复  |  直到 12 年前
        1
  •  5
  •   Jon Skeet    15 年前

    好吧,你可以用反思来做。例如:

    public static void ShowProperties(object o)
    {
        if (o == null)
        {
            Console.WriteLine("Null: no properties");
            return;
        }
        Type type = o.GetType();
        var properties = type.GetProperties(BindingFlags.Public 
                                            | BindingFlags.Instance);
        // Potentially put more filtering in here
        foreach (var property in properties.Where
                     (p => p.CanRead && p.GetIndexParameters().Length == 0))
        {
            Console.WriteLine("{0}: {1}", property.Name, property.GetValue(o, null));
        }
    }
    

    看看这个 Type 获取方法、事件、字段、嵌套类型等的API。

        2
  •  1
  •   James    15 年前

    看一看 Reflection

        3
  •  0
  •   BlackICE    15 年前

    可以使用反射来确定对象具有哪些属性、方法和字段。看看上面的方法 Type