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

iam*_*ous 2 c#

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

谢谢.

PS:我想不出任何其他细节,请问我这是不够的!

Jon*_*eet 5

好吧,你可以用反射来做.例如:

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));
    }
}
Run Code Online (Sandbox Code Playgroud)

查看Type API以获取方法,事件,字段,嵌套类型等的方法.