可能重複:
How can I code a C# function to accept a variable number of parameters?如何從一個方法內動態更新類的不同字段?
我有下面的類:
public class Product : AuditableTable
{
public string Position { get; set; }
public string Quantity { get; set; }
public double Location { get; set; }
}
我需要的是能夠與下面的函數來更新類領域。
參數:
- 交流和Pr定義的按鍵,使我得到這個類的一個實例。
- fld是要更新的類的字段名稱。它可以是「位置」,「數量」或「位置」或?
- val是值。這可能是類似「倫敦」或「1.234」
我如何安排進行動態設置的字段名稱不使用的情況下,語句 檢查FLD和許多不同的setter方法的每個值。另外,如果有一些動態設置字段 的方法,我該如何處理將其轉換爲該字段的正確對象類型?
public void Update(string ac, string pr, string fld, string val)
{
try
{
vm.Product = _product.Get(ac, pr);
vm.Product. xxx = fld
}
catch (Exception e) { log(e); }
}
更新
這裏是由彼得提出的解決方案:
public void Update(string ac, string pr, string fld, string val) {
try {
vm.Product = _product.Get("0000" + ac, pr);
if (vm.Product != null)
{
var property = vm.Product.GetType().GetProperty(fld);
var type = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType;
val = Convert.ChangeType(val, type);
property.SetValue(vm.Product, val, null);
}
_product.AddOrUpdate(vm.Product);
}
catch (Exception e) { log(e); }
}
嗯,還沒有這得到回答[這裏](HTTP://計算器。COM/A /1106367分之8663926)? – Adam 2011-12-29 10:04:21
重複創建有什麼意義? – codeSetter 2011-12-29 10:09:57
以前給出的答案不起作用,因爲設置值試圖設置vm而不是vm.Prouct。看看這個線程,我能夠進一步得到一點,但仍然有一個問題,因爲沒有答案將數據類型轉換考慮在內:-( – 2011-12-29 11:13:43