简体   繁体   English

如何使用反射在Winforms C#中为字段设置值

[英]How to Set Value for Field in winforms c# using Reflection

My Project have this: 我的项目有:

private clsDTO_Error DTO_Error; --> Have PropertyName = ID
private clsDTO_Right DTO_Right;
FieldInfo f = this.GetType().GetField(DTO_Error, BindingFlags.NonPublic | BindingFlags.Instance);

This example is working properly 这个例子工作正常

DTO_Right.GetType().GetProperty(PropertyName).SetValue(DTO_Right, "OK", null); DTO_Right.GetType()。GetProperty(PropertyName).SetValue(DTO_Right,“ OK”,null);

or 要么

f.FieldType.GetProperty("ID").SetValue(DTO_Error,"OK",null); f.FieldType.GetProperty(“ ID”)。SetValue(DTO_Error,“ OK”,null);

I have a problem in this: 我有一个问题:

f.FieldType.GetProperty("ID").SetValue(f.FieldType,"ERROR",null); f.FieldType.GetProperty(“ ID”)。SetValue(f.FieldType,“ ERROR”,null);

Any ideas for this? 有什么想法吗?

Thanks! 谢谢!

maybe: 也许:

f.FieldType.GetProperty("ID").SetValue(this,"ERROR",null); f.FieldType.GetProperty(“ ID”)。SetValue(this,“ ERROR”,null);

I have my answer that I use Directionary 我有我使用Directionary答案

private Dictionary<string, object> myDictionary = new Dictionary<string, object>();
//Add this in Form Load
myDictionary.Add("DTO_Error", DTO_Error);
//Set Value
PropertyInField.SetValue(myDictionary[DTO_Error], "OK", null);

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

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