当前位置: 首页 > 编程语言 > C#

使用属性名设置属性值分享

时间:2023-04-10 14:57:51 C#

设置属性值使用属性名可能重复:我可以使用反射来设置属性值吗?当我只有属性的字符串名称时,如何使用反射设置类的静态属性?例如我有:List_lObjects=GetObjectsList();foreach(KeyValuePair_pairin_lObjects){//类将此静态属性名称存储在_pair.KeyClass1.[_pair.Key]=(castusingtypeof(_pair.Value))_pair.Value;我不知道如何使用属性名称字符串设置属性的值。一切都充满活力。我可以设置类的5个静态属性,列表中有5个项目,每个项目都有不同的类型。感谢您的帮助。答案:Type_type=Type.GetType("Namespace.AnotherNamespace.ClassName");PropertyInfo_propertyInfo=_type.GetProperty("Field1");_propertyInfo.SetValue(_type,_newValue,null);您可以尝试这样的操作List>_lObjects=GetObjectsList();varclass1=newClass1();varclass1Type=typeof(class1);foreach(KeyValuePair_pairin_lObjects){//类将此静态属性名称存储在_pair.Keyclass1Type.GetProperty(_pair.Key).SetValue(class1,_pair.Value);您可以获得PropertyInfo并像这样设置值propertyInfo.SetValue(obj,value,null);像这样:以上就是C#学习教程:使用属性名设置属性值分享全部内容。如果对大家有用,需要详细了解C#学习教程,希望大家多多指教返回;}publicWidget(intx){this.InstanceWidgetProperty=x;返回;}publicstaticintStaticWidgetProperty{得到;放;}公共我ntInstanceWidgetProperty{得到;放;}}classProgram{staticvoidMain(){WidgetmyWidget=newWidget(-42);setStaticProperty(typeof(Widget),"StaticWidgetProperty",72);setInstanceProperty(myWidget,"InstanceWidgetProperty",123);返回;}staticvoidsetStaticProperty(Typetype,stringpropertyName,PROPERTY_TYPEvalue){PropertyInfopropertyInfo=type.GetProperty(propertyName,BindingFlags.Public|BindingFlags.Static,null,typeof(PROPERTY_TYPE),newType[0],null);propertyInfo.SetValue(null,value,null);返回;}staticvoidsetInstanceProperty(objectinstance,stringpropertyName,PROPERTY_TYPEvalue){Typetype=instance.GetType();PropertyInfopropertyInfo=type.GetProperty(propertyName,BindingFlags.Instance|BindingFlags.Public,null,typeof(PROPERTY_TYPE),newType[0],null);propertyInfo.SetValue(实例,值,null);返回;}}本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如有转载请注明出处: