public class MyClass
{
public int Age { get; set; }
public int Name { get; set; }
}
class Program
{
public static void Main()
{
MyClass tmp_Class = new MyClass();
tmp_Class.Age = 12;
Console.WriteLine(GetProperty(tmp_Class, "Age"));
SetProperty(tmp_Class, "Age", 25);
Console.WriteLine(GetProperty(tmp_Class, "Age"));
Console.Read();
}
private static void SetProperty<T>(T obj, string argName, object value)
where T : class
{
Type type = obj.GetType();
PropertyInfo propertyInfo = type.GetProperty(argName); //获取指定名称的属性
propertyInfo.SetValue(obj, value, null); //给对应属性赋值
}
private static object GetProperty<T>(T obj, string argName)
where T : class
{
Type type = obj.GetType();
PropertyInfo propertyInfo = type.GetProperty(argName); //获取指定名称的属性
return propertyInfo.GetValue(obj, null); //获取属性值
}
}