我有一个包含很少属性的类RspServer(Getters / Setter)。对于每个属性,我都有一个与之关联的属性。 服务器返回一个NameValueCollection对象,该对象包含密钥& RspServer类的值。 如何使用Reflection从NameValueCollection对象获取此类RspServer的值。 请指教
public class RspServer
{
private string _receiptNum,_respCode;
[Description("Receipt Number")]
public string ReceiptNum
{
get { return _receiptNum; }
set { _receiptNum = value; }
}
[Description("Response Code")]
public string RespCode
{
get { return _respCode; }
set { _respCode = value; }
}
}
答案 0 :(得分:1)
不应该得到你想要得到的结果,但这应该有所帮助:
RspServer server = new RspServer();
Type ClassType = server.GetType();
Dictionary<string, string> Description2Value = new Dictionary<string, string>();
foreach (PropertyInfo pi in ClassType.GetProperties().Where(pi => Attribute.IsDefined(pi, typeof(Description))))
{
Description d = (Description)pi.GetCustomAttributes(typeof(Description), false)[0];
string PropVal = (string)pi.GetValue(server);
Description2Value.Add(d.Value, PropVal);
}