问题
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
ICustomTypeDescriptororIDynamicMetaObjectProvider- which will allow some frameworks to treat it as though it had aName1, even though it actually doesn't (note: things likeDynamicObjectandExpandoObjectinclude implementations ofIDynamicMetaObjectProvider, 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