简体   繁体   English

在运行时更改属性名称

[英]Change a property name at runtime

Can I change the field of a class at runtime in c#? 我可以在运行时在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? 我可以在运行时使用反射或其他技术对其进行更改,以将Name更改为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 快速创建一个新类型,该类型看起来很像ExampleClass ,但是具有不同的成员-大概它们之间有一些映射代码
  • 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) 如果意图是用于某种类型的运行时绑定,请考虑使用ICustomTypeDescriptorIDynamicMetaObjectProvider它将允许某些框架将其视为具有Name1 ,即使实际上没有(注意:诸如DynamicObjectExpandoObject类的东西都包含IDynamicMetaObjectProvider实现) ,但您可以通过其他方式进行操作)
  • use an indexer, ie so that var val = obj["Name1"]; 使用索引器,即var val = obj["Name1"]; returns something meaningful 返回有意义的东西

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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