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

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#中通过属性名字符串获取对象属性值的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注创新互联成都网站设计公司行业资讯频道,感谢各位的阅读!
另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。