简体   繁体   English

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

[英]How to access contents of Object If I don't know the structure in c#?

I have an object and I don't know its structure until runtime. 我有一个对象,直到运行时才知道其结构。 So is there any way to access data from the object ? 那么有什么方法可以从对象访问数据?

Thanks. 谢谢。

PS: I can't think of any other details to provide, please ask me if this isn't enough! PS:我想不出其他细节,请问我是否还不够!

Well, you can do with with reflection. 好吧,你可以做反射。 For example: 例如:

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));
    }
}

Look at the Type API for ways to get methods, events, fields, nested types etc. 查看Type API,了解获取方法,事件,字段,嵌套类型等的方法。

看看反射

You can use reflection to determine what properties, methods, and fields an object has. 您可以使用反射来确定对象具有哪些属性,方法和字段。 take a look at the methods on the Type type 看一下Type类型的方法

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何比较两个 IEnumerable<T> 在 C# 中,如果我不知道实际的对象类型? - How to compare two IEnumerable<T> in C# if I don't know the actual object type? 当我事先不知道密钥时,如何在 C# 中解析 JSON 对象? - How do I parse a JSON object in C# when I don't know the key in advance? 当我不知道键和属性没有名称时,如何在 C# 中解析 JSON 对象? - How do I parse a JSON object in C# when I don't know key and properties don't have names? c#中不知道怎么减少嵌套代码 - I don't know how to reduce nesting code in c# 我不知道这个c#模式/结构/代码被调用了什么 - I don't know what this c# pattern/structure/code is called 我需要做一个 python 项目,但我知道 C# 并且不知道如何转换它 - I need to make a python project but I know C# and don't know how to convert it 如果我不知道数据结构,如何将 JSON 转换为匿名 object? - How to convert JSON to an anonymous object if I don't know the data structure? C#NullReferenceException,但我不知道是什么原因引起的 - C# NullReferenceException, but I don't know what's causing it 如果我不知道GUID,如何使用c#在Microsoft CRM上检索一条记录? - How do I retrieve a single record on Microsoft CRM using c# if I don't know the GUID? 如何将对象转换为C ++ / CLI中不知道其类型参数的通用列表? - How can I cast an Object to a generic List I don't know the type parameter of in C++/CLI?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM