简体   繁体   中英

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. 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. Couldn't get way how to get it done. Can some help. Thanks in Advance. 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. 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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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