Home >Backend Development >C++ >How to Retrieve Properties and Values from a .NET 4 Dynamic Object?

How to Retrieve Properties and Values from a .NET 4 Dynamic Object?

DDD
DDDOriginal
2025-01-22 23:17:15171browse

How to Retrieve Properties and Values from a .NET 4 Dynamic Object?

Retrieving properties from dynamic objects in .NET 4

Dynamic objects declared using the dynamic keyword in .NET 4 can cause challenges when trying to retrieve property values ​​via reflection.

Question:

How to get a dictionary of attribute names and their corresponding values ​​from a dynamic object?

Example:

<code class="language-csharp">dynamic s = new ExpandoObject();
s.Path = "/Home";
s.Name = "Home";

// 如何枚举 Path 和 Name 属性并检索它们的值?
IDictionary<string, object> propertyValues = ???</code>

Answer:

For ExpandoObject objects, the solution is very simple. ExpandoObject implements the IDictionary<string, object> interface for its properties:

<code class="language-csharp">IDictionary<string, object> propertyValues = (IDictionary<string, object>)s;</code>

Please note that this method may not work for all dynamic objects. For more general dynamic objects, you need to use the DLR via IDynamicMetaObjectProvider.

The above is the detailed content of How to Retrieve Properties and Values from a .NET 4 Dynamic Object?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn