using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
public class userInfo
{
public string UserName { get; set; }
public string PassWord { get; set; }
public object GetValue(string attributeName)
{
return this.GetType().GetProperty(attributeName).GetValue(this, null);
}
public void SetValue<T>(string attributeName, T value)
{
this.GetType().GetProperty(attributeName).SetValue(this, value);
}
public bool ContainProperty(object instance, string propertyName)
{
if (instance != null && !string.IsNullOrEmpty(propertyName))
{
PropertyInfo _findedPropertyInfo = instance.GetType().GetProperty(propertyName);
return (_findedPropertyInfo != null);
}
return false;
}
}
class 使用范例
{
private void FrmMain_Load(object sender, EventArgs e)
{
userInfo muserInfo = new userInfo();
muserInfo.UserName = "默认值";
var propNameVal = muserInfo.GetType().GetProperty("UserName").GetValue(muserInfo, null);
MessageBox.Show("初始UserName值为:" + propNameVal.ToString());
var newValue = "七月七日晴";
muserInfo.GetType().GetProperty("UserName").SetValue(muserInfo, newValue);
MessageBox.Show("修改之后的UserName值为:" + newValue.ToString());
}
}