Change a property name at runtime

2019-08-16 08:29发布

问题:

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