[英]Can I use reflection and a string to get/set the correct property of an object?
我正在使用C#和.NET 3.5。 供應商給我們提供了一個對象,該對象的屬性為UserVarNbr1,UserVarData1,UserVarNbr2,UserVarData2,... UserVarNbrN,UserVarDataN。 不是我編寫代碼的方式,但是,這是我們必須使用的方式。 應用程序中的另一個對象返回用於表示這些UserVariable的項目的集合。
收集項目具有這樣的屬性
public string VariableName
{
get { return _VariableName; }
set { _VariableName = value; }
}
public string VariableData
{
get { return _VariableData; }
set { _VariableData = value; }
}
我需要遍歷集合,並創建供應商對象的實例並設置正確的屬性。 UserVarNbrN,UserVarDataN需要放置在正確的位置。 請注意,集合以字符串“ 03”的形式返回VariableName,這需要驅動VendorObject屬性UserVarNbr3,UserVarData3 **注意,實際屬性名稱中不存在“ 0”。 如何引用正確的屬性來獲取/設置?
var o = new VendorObj();
到目前為止,我有這樣的事情。
foreach (var item in userVars)
{
const string propPrefix = "UserVar";
int varNum;
var isNum = int.TryParse(item.VariableName, out varNum);
if(isNum)
{
PropertyInfo pi;
//this is where I am stuck
// I need to set the corresponding properties on o
// example if varNum == 38, how do I reference
// o.(propPrefix+"Nbr"+varNum.ToString())
// and
// o.(propPrefix+"Data"+varNum.ToString())
// so I may set them?
}
}
任何幫助表示贊賞。 當我反思時,我是一個菜鳥。
謝謝,〜ck在聖地亞哥
VendorObj vndr = new VendorObj();
Console.WriteLine("\nInitial value of instance property: {0}", vndr.InstanceProperty);
PropertyInfo piInstance = typeof(VendorObj).GetProperty("InstanceProperty");
Object obj = piInstance.GetValue(vndr, null);
piInstance.SetValue(vndr, 37, null);
Console.WriteLine("Final value of instance property: {0}", vndr.InstanceProperty);
嘗試這個:
const string propPrefix = "UserVar";
VendorObj o = new VendorObj();
foreach (var item in userVars)
{
int varNum = 0;
if (Int32.TryParse(item.VariableName, out varNum))
{
string name = String.Format("{0}Nbr{1}", propPrefix, varNum);
o.GetType().GetProperty(name).SetValue(o, "some value", null);
}
}
由於將在一個對象上設置許多屬性,因此最好獲取PropertyDescriptorCollection
var o = new VendorObj();
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(o);
foreach (var item in userVars)
{
const string propPrefix = "userVar";
int varNum;
if (int.TryParse(item.VariableName, out varNum))
{
PropertyDescriptor property = properties.Find(propPrefix + "Nbr" + varNum, true);
property.SetValue(o, item.VariableData);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.