可能重复:
如何编写C#函数以接受可变数量的参数?
我有以下课程:
public class Product : AuditableTable
{
public string Position { get; set; }
public string Quantity { get; set; }
public double Location { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我需要的是能够使用以下函数更新类中的字段.
参数:
如何安排动态设置字段名称而不使用case语句来检查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); }
}
Run Code Online (Sandbox Code Playgroud)
更新
这是Pieter提出的解决方案:
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); }
}
Run Code Online (Sandbox Code Playgroud)
你可以使用反射:
vm.Product.GetType().GetProperty(field).SetValue(vm.Product, val, null);
Run Code Online (Sandbox Code Playgroud)
SetValue要求值的类型正确.如果不是这种情况,您可以使用以下内容进行转换:
var property = vm.Product.GetType().GetProperty(field);
// Convert.ChangeType does not work with nullable types, so we need
// to get the underlying type.
var type = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType;
object convertedValue = Convert.ChangeType(val, type);
property.SetValue(vm.Product, convertedValue, null);
Run Code Online (Sandbox Code Playgroud)
这会val在分配之前自动转换为属性的类型.
但请注意,两者都使用反射并且Convert.ChangeType速度非常慢.如果你这么做,你应该看看DynamicMethod.
| 归档时间: |
|
| 查看次数: |
963 次 |
| 最近记录: |