C# 获取 PropertyInfo 值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9081193/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get PropertyInfo value
提问by Johan
I'm trying to get the value from a PropertyInfo[], but I can't get it to work:
我试图从 a 获取值PropertyInfo[],但我无法让它工作:
foreach (var propertyInfo in foo.GetType().GetProperties())
{
var value = propertyInfo.GetValue(this, null);
}
Exception:
Object does not match target type.
例外:
Object does not match target type.
Isn't this how it's supposed to be done?
这不是应该怎么做吗?
采纳答案by Jon Skeet
You're trying to get properties from thiswhen you originally fetched the PropertyInfos from foo.GetType(). So this would be more appropriate:
您试图从this最初PropertyInfo从 中获取s时获取属性foo.GetType()。所以这会更合适:
var value = propertyInfo.GetValue(foo, null);
That's assuming you want to effectively get foo.SomePropertyetc.
那是假设你想有效地得到foo.SomeProperty等。
回答by Justin Niessner
You're getting that exception because thisisn't the same type as foo.
您收到该异常是因为this与foo.
You should make sure you're getting the properties for the same object that you're going to try to get the value from. I'm guessing from your code that you're expecting this to be foo inside the scope of the loop (which isn't the case at all), so you need to change the offending line to:
您应该确保获取的是您将尝试从中获取值的同一对象的属性。我从您的代码中猜测您希望这是循环范围内的 foo (根本不是这种情况),因此您需要将违规行更改为:
var value = propertyInfo.GetValue(foo, null);
回答by Ondrej Tucny
You are processing properties declared in foo's type, but try to read their values from this, which apparently isn't of the same type.
您正在处理在foo的类型中声明的属性,但尝试从 中读取它们的值this,这显然不是同一类型。

