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"