Change a property name at runtime

守給你的承諾、 提交于 2019-12-13 04:27:51

问题


Can I change the field of a class at runtime in c#?

for example, if i have the class:

public class ExampleClass{
    public string Name;
}

can I Change it at runtime, using reflection or other techniques, to change the Name to Name1?

public class ExampleClass{
    public string Name1;
}

回答1:


No, you cannot change the actual members of a type at runtime

Options:

  • create a new type on the fly, that looks a lot like ExampleClass, but has different members - and presumably some mapping code between them
  • if the intent is for some kind of runtime binding, consider ICustomTypeDescriptor or IDynamicMetaObjectProvider - which will allow some frameworks to treat it as though it had a Name1, even though it actually doesn't (note: things like DynamicObject and ExpandoObject include implementations of IDynamicMetaObjectProvider, but you can do it in other ways)
  • use an indexer, i.e. so that var val = obj["Name1"]; returns something meaningful



回答2:


Have a look at DynamicObject:

http://msdn.microsoft.com/en-us/library/system.dynamic.dynamicobject.aspx



来源:https://stackoverflow.com/questions/17109397/change-a-property-name-at-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!