[英]How to find generic property name of class instance and how to assign value to the property run time
I have following classes. 我有以下课程。 In instance of BE (let's say objBE) i want to select property name on run time and assign it's value.
在BE的实例中(假设objBE),我想在运行时选择属性名称并分配其值。 eg we have a combo with all properties populated, and have text box and command button on window form.
例如,我们有一个组合了所有属性的组合,并且在窗口窗体上有文本框和命令按钮。 I want to select property name from the combo and type some value in text box and on button click i want to find the property name from the objBE and assign the text box value to the selected property.
我想从组合中选择属性名称,然后在文本框中键入一些值,然后单击按钮,我想从objBE中找到属性名称,并将文本框值分配给选定的属性。 Couldn't get way how to get it done.
无法获得如何完成它的方法。 Can some help.
可以帮忙。 Thanks in Advance.
提前致谢。 HN
HN
public class MyPropertyBase
{
public int StartOffset { get; set; }
public int EndOffset { get; set; }
}
public class MyProperty<T> : MyPropertyBase
{
public MyProperty(T propertyValue)
{
PropertyValue = propertyValue;
}
public T PropertyValue { get; set; }
public static implicit operator MyProperty<T>(T t)
{
return new MyProperty<T>(t);
}
}
public class BE
{
private List<Admin_Fee> _Admin_Fee = new List<Admin_Fee>();
public MyProperty<int> RFID
{get;set;}
public MyProperty<string> CUSIP
{get;set;}
public MyProperty<string> FUND_CITY
{get;set;}
public MyProperty<int> SomeOtherProperty { get; set; }
//public List<MyPropertyBase> MyDataPoints { get; set; }
public List<Admin_Fee> Admin_Fee
{
get{return _Admin_Fee;}
set{}
}
}
You can use GetProperty
on the Type
, then use SetValue
on the PropertyInfo
instance. 您可以在
Type
上使用GetProperty
,然后在PropertyInfo
实例上使用SetValue
。 Based on your description, I think you want something like this: 根据您的描述,我认为您需要这样的东西:
void Main()
{
BE be = new BE();
SetMyPropertyValue("RFID", be, 2);
SetMyPropertyValue("CUSIP", be, "hello, world");
Console.WriteLine(be.RFID.PropertyValue);
Console.WriteLine(be.CUSIP.PropertyValue);
}
private void SetMyPropertyValue(string propertyName, object instance, object valueToSet)
{
Type be = instance.GetType();
Type valueType = valueToSet.GetType();
Type typeToSet = typeof(MyProperty<>).MakeGenericType(valueType);
object value = Activator.CreateInstance(typeToSet,valueToSet);
var prop = be.GetProperty(propertyName);
prop.SetValue(instance, value, null);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.