读书人

[C#]关于一个反射的有关问题

发布时间: 2012-01-23 21:57:28 作者: rapoo

[C#]关于一个反射的问题。
public struct dfInfoPic
{
decimal _ID;
public decimal ID
{
get { return
_ID; }
set { _ID = value; }
}
}

private T test<T>(T df,string property) where T : struct
{
df.GetType().GetProperty(property).SetValue(df, 3m, null);
return df;
}

dfInfoPic df = new dfInfoPic();
df.ID = 1m;
Response.Write(df.ID);
Response.Write("<br/>");
object sid = df;
sid.GetType().GetProperty("ID").SetValue(sid, 2m, null);

Response.Write(((dfInfoPic)sid).ID);
Response.Write("<br/>");
Response.Write(this.test<dfInfoPic>(df, "ID").ID);


预计结果应该是:
1
2
3
但现在的运行结果却是
1
2
1

想问一下,两行红色部份的代码有什么不同?

[解决办法]
private T test <T >(T df,string property) where T : struct
{
object t = df;
df.GetType().GetProperty(property).SetValue(t, 3m, null);
return (T)t;
}

跟反射没关系,看下装拆箱和传值。

读书人网 >C#

热点推荐