验证中...
反射获取字段值和设置值
原始数据 复制代码
1,通过反射去了解一个类里面的属性
a,首先创建一个类
public class Student
{
public string StudentID { get; set; }
public string StudentName { get; set; }
}
b,构建方法去获取类里面指定字段的值
/// <summary>
/// 获取指定字段值
/// </summary>
/// <param name="fileName"></param>
/// <param name="obj"></param>
/// <returns></returns>
public static string GetFiledValue(string fileName, object obj)
{
try
{
Type type = obj.GetType(); //获取当前传递类的类型
object o = type.GetProperty(fileName).GetValue(obj, null); //找到指定字段,然后从第一步里面获取值
string value = o.ToString();
return value;
}
catch (Exception)
{
return null;
}
}
/// <summary>
/// 设置字段的值
/// </summary>
/// <param name="fileName"></param>
/// <param name="value"></param>
/// <param name="obj"></param>
/// <returns></returns>
public static bool SetModelValue(string fileName, string value, object obj)
{
try
{
Type type = obj.GetType();
//object change = Convert.ChangeType(value, type.GetProperty(fileName).PropertyType);
type.GetProperty(fileName).SetValue(obj, value, null);
return true;
}
catch (Exception)
{
return false;
}
}
c,调用方式
Student stu = new Student() { StudentID = "Test001", StudentName = "Test" };
//var showStudentId = GetFiledValue("StudentID", stu);
//Console.WriteLine(showStudentId);
bool flag = SetModelValue("StudentName", "Admin", stu);
Console.WriteLine(flag);
Console.WriteLine(stu.StudentName);

评论列表( 0 )

你可以在登录后,发表评论

搜索帮助