动态向现有对象添加属性 [英] Dynamically add properties to a existing object

查看:71
本文介绍了动态向现有对象添加属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我这样创建人员对象。

 Person person=new Person("Sam","Lewis") 

它具有这样的属性。

person.Dob
person.Address

但是现在我想要添加这样的属性并在创建对象后在运行时设置值。
person.Age
person.Sex

But now I want to add properties like this and set the values at the run time after creating the object. person.Age person.Sex

创建对象后如何添加这些额外的属性。这些属性名称可以不时更改。因此无法对年龄和性别进行硬编码。

How can I add those extra properties after creating the object. Those property name can be changed time to time. Therefor can't hardcode the "Age" and "Sex".

推荐答案

使用普通对象是不可能的,但是您可以使用 ExpandoObject dynamic 关键字来实现:

It's not possible with a "normal" object, but you can do it with an ExpandoObject and the dynamic keyword:

dynamic person = new ExpandoObject();
person.FirstName = "Sam";
person.LastName = "Lewis";
person.Age = 42;
person.Foo = "Bar";
...

如果您尝试分配不存在的属性,它将被添加到对象。如果您尝试读取一个不存在的属性,它将引发异常。因此,它的行为与字典大致相同(ExpandoObject实际上实现了 IDictionary< string,object>

If you try to assign a property that doesn't exist, it is added to the object. If you try to read a property that doesn't exist, it will raise an exception. So it's roughly the same behavior as a dictionary (and ExpandoObject actually implements IDictionary<string, object>)

这篇关于动态向现有对象添加属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆