+-

我在MSSQL数据库中有一个约300列的表格,我只想提取一行并获取列的所有值.我使用了这段代码,但是GetValue(,)方法存在问题.这是我的代码:
private PropertyInfo[] GetValuesDB()
{
......
var result = from val in datacTx.TableA
where val.A == "AA" + "-" + "11" &&
val.B == "CC
select val;
return result.First().GetType().GetProperties();
}
...
public void MethodA()
{
var res = GetValuesDB();
foreach (var propertyInfo in res)
{
var rez = propertyInfo.GetValue(res,null);
}
}
我总是得到这种例外:
Object does not match target type.
最佳答案
GetValue期望第一个参数的类型是声明属性(或子类型)的类型.
因此,您的result.First()调用返回对对象的引用-并且您想要获取该对象的属性…因此,该引用应该是您传递给GetValue的引用.您需要更改代码以返回该引用:
// Ideally, change this to a more appropriate return type...
private object GetValuesDB()
{
......
var result = from val in datacTx.TableA
where val.A == "AA" + "-" + "11" &&
val.B == "CC"
select val;
return result.First();
}
...
public void MethodA()
{
var res = GetValuesDB();
foreach (var propertyInfo in res.GetType().GetProperties())
{
var rez = propertyInfo.GetValue(res, null);
}
}
因此,GetValuesDB现在返回对相关实体的引用-然后您获取属性描述符,并向每个描述符询问该对象上该属性的值.
点击查看更多相关文章
转载注明原文:c#-属性的GetValue - 乐贴网