C#通过属性名字符串获取、设置对象属性值
2021-01-17 12:14
标签:ext static find for list public 目录 封装 end 目录 C#通过属性名字符串获取、设置对象属性值 标签:ext static find for list public 目录 封装 end 原文地址:https://www.cnblogs.com/willingtolove/p/12198871.html
#通过反射获取对象属性值并设置属性值
0、定义一个类
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public string Age { get; set; }
}
1、通过属性名(字符串)获取对象属性值
User u = new User();
u.Name = "lily";
var propName = "Name";
var propNameVal = u.GetType().GetProperty(propName).GetValue(u, null);
Console.WriteLine(propNameVal);// "lily"
2、通过属性名(字符串)设置对象属性值
User u = new User();
u.Name = "lily";
var propName = "Name";
var newVal = "MeiMei";
u.GetType().GetProperty(propName).SetValue(u, newVal);
Console.WriteLine(propNameVal);// "MeiMei"
#获取对象的所有属性名称及类型
User u = new User();
foreach (var item in u.GetType().GetProperties())
{
Console.WriteLine($"propName:{item.Name},propType:{item.PropertyType.Name}");
}
// propName: Id,propType: Int32
// propName:Name,propType: String
// propName:Age,propType: String
foreach (var item in typeof(User).GetProperties())
{
Console.WriteLine($"propName:{item.Name},propType:{item.PropertyType.Name}");
}
// propName: Id,propType: Int32
// propName:Name,propType: String
// propName:Age,propType: String
#判断对象是否包含某个属性
static void Main(string[] args)
{
User u = new User();
bool isContain= ContainProperty(u,"Name");// true
}
public static bool ContainProperty( object instance, string propertyName)
{
if (instance != null && !string.IsNullOrEmpty(propertyName))
{
PropertyInfo _findedPropertyInfo = instance.GetType().GetProperty(propertyName);
return (_findedPropertyInfo != null);
}
return false;
}
public static class ExtendLibrary
{
///
static void Main(string[] args)
{
User u = new User();
bool isContain= u.ContainProperty("Name");// true
}
文章标题:C#通过属性名字符串获取、设置对象属性值
文章链接:http://soscw.com/index.php/essay/43187.html