简体   繁体   中英

Change a property name at runtime

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;
}

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, ie so that var val = obj["Name1"]; returns something meaningful

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM