//Using System.Linq;引用命名空间
/// <summary>
/// 利用反射根据对象和属性名取对应属性的值
/// </summary>
/// <param name="feildname"></param>
/// <param name="obEntity"></param>
/// <returns></returns>
public string GetValueByPropertyName(string feildname, Object obEntity)
{
string PropertyVaule = string.Empty;
Type tpEntity = obEntity.GetType();
System.Reflection.PropertyInfo[] pis = tpEntity.GetProperties();
var a=pis.FirstOrDefault(m=>m.Name==feildname);
if (a!=null)
{
object obj= a.GetValue(obEntity, null);
if (obj != null)
{
PropertyVaule = obj.ToString();
}
break;
}
return PropertyVaule;
}
/// <summary>
/// 利用反射根据对象和属性名为对应的属性赋值
/// </summary>
/// <param name="feildname"></param>
/// <param name="obEntity"></param>
/// <returns></returns>
public void SetValueByPropertyName(string feildname, Object obEntity,string Value)
{
Type tpEntity = obEntity.GetType();
System.Reflection.PropertyInfo[] pis = tpEntity.GetProperties();
var a=pis.FirstOrDefault(m=>m.Name==feildname);
if (a!=null)
{
a.SetValue(obEntity, Convert.ChangeType(Value,a.PropertyType),null);
return;
}
}
}
最后
以上就是明亮薯片最近收集整理的关于利用反射给对象中的某个属性赋值或取值的全部内容,更多相关利用反射给对象中内容请搜索靠谱客的其他文章。
发表评论 取消回复