使用变量调用动态方法/参数 [英] Use variables to call dynamic methods / parameters
本文介绍了使用变量调用动态方法/参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
你好,
我正在尝试从动态对象动态获取所有属性及其值.
这是我到目前为止的代码:
Hi there,
I''m trying to dynamically get all properties and their values from dynamic objects.
This is the code I have so far:
//The code that should show the parameter and the parameter value
class MdlObject
{
public void Insert(dynamic anObject)
{
var propertyInfos = anObject.GetType().GetProperties();
// sort properties by name
// write property names
foreach (var propertyInfo in propertyInfos)
{
//this works perfect, returns Name and Id
MessageBox.Show(propertyInfo.Name);
//Gives an error, because it literally calls "anObject.propertyInfo.Name"
MessageBox.Show(anObject.propertyInfo.Name);
//This works, thanks Nishant Sivakumar :)
MessageBox.Show(propertyInfo.GetValue(anObject, null).ToString());
}
}
//Example of a simple object I want to put in
class Mdltest
{
public String Name { get; set; }
public int Id { get; set; }
}
//Example of how to call it
var test= new Mdltest{Id = 10, Name = "just testing"};
var tmp = new MdlObject();
tmp.Insert(test);
有人可以告诉我如何修复"anObject.propertyInfo.Name"部分吗?因为当我使用它时,它实际上是调用"anObject.propertyInfo.Name",而不是例如anObject.Name和anObject.Id ...
预先感谢您的帮助:)
Gr.
Could someone tell me how I''m suppose to fix the "anObject.propertyInfo.Name" part? because when I use that it literally calls "anObject.propertyInfo.Name", and not for example anObject.Name and anObject.Id ...
Thanks in advance for the help :)
Gr.
推荐答案
那行不通,您可以这样操作:
That won''t work, you can do it this way:
class MdlObject
{
public void Insert(dynamic anObject)
{
var propertyInfos = anObject.GetType().GetProperties();
foreach (var propertyInfo in propertyInfos)
{
MessageBox.Show(propertyInfo.Name);
}
MessageBox.Show(anObject.Name);
MessageBox.Show(anObject.Id.ToString());
}
}
或执行以下操作:
Or do this:
foreach (var propertyInfo in propertyInfos)
{
MessageBox.Show(propertyInfo.Name);
MessageBox.Show(propertyInfo.GetValue(anObject, null).ToString());
}
您需要在PropertyInfo上调用GetValue方法,传入要查询的对象.
You need to call the GetValue method on the PropertyInfo, passing in the object you want to query.
这篇关于使用变量调用动态方法/参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文