在运行时更改属性名称 [英] Change a property name at runtime

查看:73
本文介绍了在运行时更改属性名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以在运行时在C#中更改类的字段吗?

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

我可以在运行时使用反射或其他方法将其更改为将Name更改为Name1吗?

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

选项:

  • 动态创建一个新类型,看起来很像 ExampleClass ,但是具有不同的成员-大概它们之间有一些映射代码
  • 如果意图是用于某种类型的运行时绑定,请考虑使用 ICustomTypeDescriptor IDynamicMetaObjectProvider -这将允许某些框架将视为即使实际上没有,它也具有 Name1 (注意:诸如 DynamicObject ExpandoObject 之类的内容包括 IDynamicMetaObjectProvider ,但您可以通过其他方式做到)
  • 使用索引器,即 var val = obj ["Name1"]; 返回有意义的内容
  • 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

这篇关于在运行时更改属性名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆