通过一下方法反射获取类的属性,能够获取属性值或设置属性值;
注:一定要封装字段使用属性
- 通过给类添加自定义的索引器实现,伪码:
public class myclass{
//类的私有属性
private string a;
//一定要封装字段使用属性,否则GetProperty()是查询不到这个属性的
public string A{ get => A; set => A = value; }
//自定义索引器
public object this[string propertyName]
{
get
{
Type type= typeof(myclass);
PropertyInfo pi= myType.GetProperty(propertyName);
return pi.GetValue(this, null);
}
set
{
Type type= typeof(myclass);
PropertyInfo pi= myType.GetProperty(propertyName);
pi.SetValue(this, value, null);
}
}
}
//调用方式:
myclass mc = new myclass();
//设置属性值
mc["a"]=b;
//获取属性值
string a = mc["a"];
- 通过公共方法实现对所有其他类的属性获取:
/// <summary>
/// 获取类中的属性值
/// </summary>
/// <param name="FieldName">属性名称</param>
/// <param name="obj">类的实例</param>
/// <returns>属性值</returns>
public string GetModelValue(string FieldName, object obj)
{
try
{
Type type = obj.GetType();
string Value = Convert.ToString(type.GetProperty(FieldName).GetValue(obj, null));
return string.IsNullOrEmpty(Value)?null: Value;
}
catch
{
return null;
}
}
/// <summary>
/// 设置类中的属性值
/// </summary>
/// <param name="FieldName">属性名称</param>
/// <param name="Value">要设置的值</param>
/// <param name="obj">类的实例</param>
/// <returns>是否成功</returns>
public bool SetModelValue(string FieldName, string Value, object obj)
{
try
{
Type type = obj.GetType();
object v = Convert.ChangeType(Value, type.GetProperty(FieldName).PropertyType);
type.GetProperty(FieldName).SetValue(obj, v, null);
return true;
}
catch
{
return false;
}
}