2
我有以下類。在BE(假設objBE)的例子中,我想在運行時選擇屬性名稱並分配它的值。例如我們有一個包含所有填充屬性的組合,並且在窗體上有文本框和命令按鈕。我想從組合中選擇屬性名稱並在文本框中鍵入一些值,然後在按鈕上單擊我想從objBE中查找屬性名稱,並將文本框的值分配給所選屬性。無法想象如何完成它。可以幫助一些。 在此先感謝。 H N如何查找類實例的通用屬性名稱以及如何爲屬性運行時指定值
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{}
}
}
我試圖分配值,如你所建議的字符串strproname =「FUND_CITY」; System.Reflection.PropertyInfo proInfo = objBe.GetType()。GetProperty(strproname); MyProperty propVal = new MyProperty (「Mark」); proInfo.SetValue(objBe,propVal,null);但在運行時,我們不會創建propVal,因爲我們無法在運行時輸入值。 –
感謝您的建議。我試圖實現代碼,但我得到null異常var prop = be.GetProperty(propertyName)。 –
這個建議看起來不錯。看起來它會爲我工作。非常感謝。但是需要更多的改進。我們可以設置值爲be.rfid = 2,我們也想設置Be.rfid.startoffset = 1500和be.RFID.EndOffset = 1502。此外,如果類型是公共列表 Admin_Fee的集合,那麼我們還需要爲每個屬性類型設置值。 –