C#反射-通过属性的路径设置值

时间:2018-12-14 11:39:39

标签: c# reflection propertyinfo

我想通过指定点分隔的路径来更新任何公共属性中的值。

但是,每当我调用方法时,都会收到以下错误消息:

pi.SetValue(instance, value1, null);

错误消息:

对象与目标类型不匹配。

我的方法:

private void SetPathValue(object instance, string path, object value)
{
    string[] pp = path.Split('.');
    Type t = instance.GetType();
    for (int i = 0; i < pp.Length; i++)
    {
        PropertyInfo pi = t.GetProperty(pp[i]);
        if (pi == null)
        {
            throw new ArgumentException("Properties path is not correct");
        }
        else
        {
            instance = pi.GetValue(instance, null);
            t = pi.PropertyType;
            if (i == pp.Length - 1)//last
            {
               // Type targetType = IsNullableType(pi.PropertyType) ? Nullable.GetUnderlyingType(pi.PropertyType) : pi.PropertyType;
                var value1 = Convert.ChangeType(value, instance.GetType());
                pi.SetValue(instance, value1, null);//ERROR
            }
        }
    }
}

private static bool IsNullableType(Type type)
{
    return type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(Nullable<>));
}

2 个答案:

答案 0 :(得分:1)

我认为您的原始版本最终将设置值“深一层”。

我认为递归模式将更容易遵循,并且需要更少的代码。这是我汇总的一个快速版本,适用于简单的测试用例。

我现在没有时间进行优化(在递归调用上重建字符串)和边缘情况(例如null检查)的几种机会,但是我认为它们将很难添加。

public void SetProperty(object target, string property, object setTo)
{
    var parts = property.Split('.');
    var prop = target.GetType().GetProperty(parts[0]);
    if (parts.Length == 1)
    {
        // last property
        prop.SetValue(target, setTo, null);
    }
    else
    {
        // Not at the end, go recursive
        var value = prop.GetValue(target);
        SetProperty(value, string.Join(".", parts.Skip(1)), setTo);
    }
}

Here是LINQPad演示,演示了它的运行情况:

void Main()
{
    var value = new A();
    Debug.WriteLine("Original value:");
    value.Dump();

    Debug.WriteLine("Changed value:");
    SetProperty(value, "B.C.D","changed!");
    value.Dump();
}

public void SetProperty(object target, string property, object setTo)
{...}

public class A
{
    public B B { get; set; } = new B();
}

public class B
{
    public C C { get; set; } = new C();
}

public class C
{
    public string D { get; set; } = "test";
}

它产生以下结果:

enter image description here

答案 1 :(得分:0)

我想完成答案Bradley Uffner

public void SetProperty (object target, string property, object setTo)
{
  var parts = property.Split ('.');
  // if target object is List and target object no end target - 
  // we need cast to IList and get value by index
  if (target.GetType ().Namespace == "System.Collections.Generic"
      && parts.Length != 1)
    {
      var targetList = (IList) target;
      var value = targetList[int.Parse (parts.First ())];
      SetProperty (value, string.Join (".", parts.Skip (1)), setTo);
    }
  else
    {
      var prop = target.GetType ().GetProperty (parts[0]);
      if (parts.Length == 1)
    {
      // last property
      prop.SetValue (target, setTo, null);
    }
      else
    {
      // Not at the end, go recursive
      var value = prop.GetValue (target);
      SetProperty (value, string.Join (".", parts.Skip (1)), setTo);
    }
    }
}