动态创建匿名类型?

发布于 2024-09-29 07:38:46 字数 104 浏览 1 评论 0原文

我想创建一个可以动态设置属性名称的匿名类型。它不必是匿名类型。我想要实现的就是动态设置任何对象属性名称。它可以是 ExpandoObject,但字典对我不起作用。

您有什么建议?

I wanna create an anonymous type that I can set the property name dynamically. it doesn't have to be an anonymous type. All I want to achieve is set any objects property names dynamically. It can be ExpandoObject, but dictionary will not work for me.

What are your suggestions?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

小帐篷 2024-10-06 07:38:46

只有 ExpandoObject 可以具有动态属性。

编辑
以下是扩展对象用法的示例(来自其MSDN 描述):

dynamic sampleObject = new ExpandoObject();
sampleObject.TestProperty = "Dynamic Property"; // Setting dynamic property.
Console.WriteLine(sampleObject.TestProperty );
Console.WriteLine(sampleObject.TestProperty .GetType());
// This code example produces the following output:
// Dynamic Property
// System.String

dynamic test = new ExpandoObject();
((IDictionary<string, object>)test).Add("DynamicProperty", 5);
Console.WriteLine(test.DynamicProperty);

Only ExpandoObject can have dynamic properties.

Edit:
Here is an example of Expand Object usage (from its MSDN description):

dynamic sampleObject = new ExpandoObject();
sampleObject.TestProperty = "Dynamic Property"; // Setting dynamic property.
Console.WriteLine(sampleObject.TestProperty );
Console.WriteLine(sampleObject.TestProperty .GetType());
// This code example produces the following output:
// Dynamic Property
// System.String

dynamic test = new ExpandoObject();
((IDictionary<string, object>)test).Add("DynamicProperty", 5);
Console.WriteLine(test.DynamicProperty);
东北女汉子 2024-10-06 07:38:46

您可以将 ExpandoObject 转换为字典并以这种方式填充它,然后您设置的键将显示为 ExpandoObject 上的属性名称...

dynamic data = new ExpandoObject();

IDictionary<string, object> dictionary = (IDictionary<string, object>)data;
dictionary.Add("FirstName", "Bob");
dictionary.Add("LastName", "Smith");

Console.WriteLine(data.FirstName + " " + data.LastName);

You can cast ExpandoObject to a dictionary and populate it that way, then the keys that you set will appear as property names on the ExpandoObject...

dynamic data = new ExpandoObject();

IDictionary<string, object> dictionary = (IDictionary<string, object>)data;
dictionary.Add("FirstName", "Bob");
dictionary.Add("LastName", "Smith");

Console.WriteLine(data.FirstName + " " + data.LastName);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文