簡體   English   中英

如何查找類實例的通用屬性名稱以及如何為屬性運行時分配值

[英]How to find generic property name of class instance and how to assign value to the property run time

我有以下課程。 在BE的實例中(假設objBE),我想在運行時選擇屬性名稱並分配其值。 例如,我們有一個組合了所有屬性的組合,並且在窗口窗體上有文本框和命令按鈕。 我想從組合中選擇屬性名稱,然后在文本框中鍵入一些值,然后單擊按鈕,我想從objBE中找到屬性名稱,並將文本框值分配給選定的屬性。 無法獲得如何完成它的方法。 可以幫忙。 提前致謝。 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{}
     }
}

您可以在Type上使用GetProperty ,然后在PropertyInfo實例上使用SetValue 根據您的描述,我認為您需要這樣的東西:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM