大可 • Duke

专注,谦逊,分享

C#动态属性赋值/取值

1.给已有对象属性赋值(批量设置属性值)

/// <summary>
/// 给现有对象属性赋值
/// </summary>
/// <param name="obj">对象</param>
/// <param name="nameValue">{ 属性名, 属性值 }</param>
private void SetPropertyValue(object obj, Dictionary<string, object> nameValue) {
    foreach (PropertyInfo pi in obj.GetType().GetProperties()) {
        if (nameValue.TryGetValue(pi.Name, out var outObj)) {
            Type outType = outObj.GetType();
            if (outType == pi.PropertyType) {
                pi.SetValue(obj, outObj, null);
            }
        }
    }
}

使用如下:

[Test]
public void Test()
{
       var myCar = new Car();
       var typeData = new Dictionary<string, object> { { "Color", "Blue" } };
       SetPropertyValue(myCar, typeData);
       Assert.AreEqual("Blue", myCar.Color);
}

internal class Car
{
    public String Color { get; set; }
}

2.返回一个新对象(批量设置属性值)

private T SetPropertyValue<T>(Dictionary<string, object> nameValue) {
          T generic = (T)Activator.CreateInstance<T>();
          foreach (PropertyInfo pi in typeOf(T).GetProperties()) {
              if (nameValue.TryGetValue(pi.Name, out var outObj)) {
                  Type outType = outObj.GetType();
                  if (outType == pi.PropertyType) {
                      pi.SetValue(generic, outObj, null);
                  }
              }
          }
          return generic;
      }

使用如下:

[Test]
public void Test()
{
       var typeData = new Dictionary<string, object> { { "Color", "Blue" } };
       var myCar = SetPropertyValue<Car>(typeData);
       Assert.AreEqual("Blue", myCar.Color);
}

internal class Car
{
    public String Color { get; set; }
}

3.也可以直接操作

a.通过属性名(字符串)获取对象属性值

 User u = new User();
 u.Name = "lily";
 var propName = "Name";
 var propNameVal = u.GetType().GetProperty(propName).GetValue(u, null);
 
 Console.WriteLine(propNameVal);// "lily"

b.通过属性名(字符串)设置对象属性值

 User u = new User();
 u.Name = "lily";
 var propName = "Name";
 var newVal = "MeiMei";
 u.GetType().GetProperty(propName).SetValue(u, newVal);
 
 Console.WriteLine(propNameVal);// "MeiMei"
posted @ 2020-08-09 17:15  大可·Duke  阅读(6041)  评论(0编辑  收藏  举报