类定义中,批量修改当前对像的的属性
User 类 成员变量中定义了很多属性userid,usename,mail,mobile,等等
定义了实例化成员函数
User (int uid)
{
this.userid = uid;
}
但其它属性是空的,定义无返回值的成员函数
Get()
{
//从数据库用LINQ查询到一个对应的实例物像,想把查询到的实例对象的对应的属性值赋给当前对像
var res = from rs in db.User where rs.UserId == this.UserId select rs;
if (res.Count() > 0)
{
User z = res.First();
//但是不能用this = z;
//也不想一个个的用属性名来复制如 this.userid = z.userid;因为成员变量比较多
//求助:能不能用反射或其它的方式达到我的目的 类成员函数对于当前对像不太会用反射,
}
}
万分感谢
[解决办法]
/// <summary>
/// 类定义
/// </summary>
public class User
{
public int userid { get; set; }
public string username { get; set; }
public string mail { get; set; }
public string mobile { get; set; }
public User(int userid)
{
this.userid = userid;
}
public void Get()
{
using (BirthdayDataClassesDataContext db = new BirthdayDataClassesDataContext())
{
TableA result = (from u in db.TableA
where u.userid == this.userid
select u).FirstOrDefault();
if (result != null)
{
PropertyInfo[] pros = typeof(TableA).GetProperties();
foreach (PropertyInfo item in pros)
{
string name = item.Name;
string value = string.Empty;
if (item.GetValue(result, null) != null)
{
value = item.GetValue(result, null).ToString();
PropertyInfo user = typeof(User).GetProperty(name);
if (user != null)
{
//如果是特殊类型需要判断、强制转换
//这里userid为int
//其他都为string
if(user.PropertyType==typeof(int))
user.SetValue(this, Convert.ToInt32(value), null);
else
user.SetValue(this, value, null);
}
}
}
}
}
}
}
static void Main(string[] args)
{
User user = new User(1001);
user.Get();
Console.WriteLine("userid:{0,-6}username:{1,-6}mail:{2,-15}mobile:{3,-15}", user.userid, user.username, user.mail, user.mobile);
Console.Read();
}