[英]I need to get a value of specific object's property, but don't know the type of the object
I have got an c# object and I don't know the type of this object.我有一个 c# object 我不知道这个 object 的类型。 (ie object o) What I know is that this object has a member called 'ID' of type int.
(即 object o)我所知道的是,这个 object 有一个名为“ID”的 int 类型的成员。
I wanted to get the value of this property but I am not good enough with reflection...我想获得这个属性的价值,但我的反射还不够好......
I can get a type and members of this object:我可以得到这个 object 的类型和成员:
Type type = obj.GetType();
System.Reflection.MemberInfo[] member = type.GetMember("ID");
...but don't know what to do next:-) ...但不知道下一步该怎么做:-)
Thanks for help in advance Mariusz提前感谢马里乌斯的帮助
You can use:您可以使用:
Type type = obj.GetType();
PropertyInfo property = type.GetProperty("ID");
int id = (int) property.GetValue(obj, null);
PropertyInfo
because you know it's a property, which makes things easierPropertyInfo
因为您知道它是一个属性,这使事情变得更容易GetValue
to get the value, passing in obj
as the target of the property and null
for indexer arguments (as it's a property, not an index)GetValue
获取值,传入obj
作为属性的目标, null
用于索引器 arguments(因为它是属性,而不是索引)int
as you already know it's going to be an int
int
,因为您已经知道它将是一个int
Jared's suggestion of using dynamic
is good too, if you're using C# 4 and .NET 4, although to avoid all the brackets I'd probably write it as: Jared 关于使用
dynamic
的建议也很好,如果您使用的是 C# 4 和 .NET 4,尽管为了避免使用所有括号,我可能会将其写为:
dynamic d = obj;
int id = d.ID;
(unless you needed it in a single expression for some reason). (除非您出于某种原因需要在单个表达式中使用它)。
Is this a public property?这是公共财产吗? Is so then the easiest route is to use
dynamic
是这样的话,最简单的路线是使用
dynamic
int value = ((dynamic)obj).ID;
Can you use C# 4?你能用 C# 4 吗? In that case, you can use
dynamic
:在这种情况下,您可以使用
dynamic
:
dynamic dyn = obj;
int id = dyn.ID;
public class TestClass
{
public TestClass()
{
// defaults
this.IdField = 1;
this.IdProperty = 2;
}
public int IdField;
public int IdProperty { get; set; }
}
// here is an object obj and you don't know which its underlying type
object obj = new TestClass();
var idProperty = obj.GetType().GetProperty("IdProperty");
if (idProperty != null)
{
// retrieve it and then parse to int using int.TryParse()
var intValue = idProperty.GetValue(obj, null);
}
var idField = obj.GetType().GetField("IdField");
if (idField != null)
{
// retrieve it and then parse to int using int.TryParse()
var intValue = idField.GetValue(obj);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.