怎么在C#中通过属性名字符串获取对象属性值?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

乌海网站建设公司创新互联公司,乌海网站设计制作,有大型网站制作公司丰富经验。已为乌海近1000家提供企业网站建设服务。企业网站搭建\外贸网站建设要多少钱,请找那个售后服务好的乌海做网站的公司定做!
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
{
///
/// 利用反射来判断对象是否包含某个属性
///
/// object
/// 需要判断的属性
/// 是否包含
public static bool ContainProperty(this object instance, string propertyName)
{
if (instance != null && !string.IsNullOrEmpty(propertyName))
{
PropertyInfo _findedPropertyInfo = instance.GetType().GetProperty(propertyName);
return (_findedPropertyInfo != null);
}
return false;
}
}
static void Main(string[] args)
{
User u = new User();
bool isContain= u.ContainProperty("Name");// true
}看完上述内容,你们掌握怎么在C#中通过属性名字符串获取对象属性值的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注创新互联行业资讯频道,感谢各位的阅读!