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;因为成员变量比较多
//求助:能不能用反射或其它的方式达到我的目的 类成员函数对于当前对像不太会用反射,
}
}万分感谢
定义了实例化成员函数
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;因为成员变量比较多
//求助:能不能用反射或其它的方式达到我的目的 类成员函数对于当前对像不太会用反射,
}
}万分感谢
2. this就是当前实例,当然不能直接赋值了
3. Get方法要返回一个User对象吗,那应该这样写User Get()
{
// 返回相同UserID的User,没有对应项时返回null
return db.User.FirstOrDefault(u => u.UserId == this.UserId);
}
我希望这样使用
User u=new (1);//初始化一个id为1的实例对像
u.Get();//查询ID为1的用户的全部信息
这样实例u就有全部用户信息了.
/// <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();
}
drop table TableAgo
create table TableA
(
userid int,
username nvarchar(20),
mail nvarchar(20),
mobile nvarchar(20)
)go
insert into TableA values
('1001','name1','[email protected]','232343'),
('1002','name2','[email protected]','542343'),
('1003','name2','[email protected]','56556')
class User {
...
// 获取详细信息
static User GetUser(int userID)
{
// 返回相同UserID的User,没有对应项时返回null
return db.User.FirstOrDefault(u => u.UserId == userId);
}
}// 调用
User u = User.GetUser(1);