[英]C# Reflection : Type cast method return value in specific type of object list
I have following assemble which contains following data 我有以下汇编,其中包含以下数据
demo.dll
Class 1 1类
namespace demo
public class Data
{
public string FirstName {get; set;}
}
Class 2 2级
namespace demo
public class Utility
{
private List<Data> items;
public Utility()
{
items = new List<Data>();
items.add(new Data(){ FirstName = "Abc" });
}
public List<Data> GetItems()
{
return items;
}
}
Now I want to load above demo.dll assemble using runtime and call GetItem()
method. 现在,我想使用运行时加载以上demo.dll组装并调用
GetItem()
方法。
For that I can write following code 为此,我可以编写以下代码
Assembly assembly = Assembly.LoadFile(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ,"demo.dll"));
Type Utility= assembly.GetType("demo.Utility");
Type Data= assembly.GetType("demo.Data");
MethodInfo GetItems = Utility.GetMethod("GetItems");
object utility = Activator.CreateInstance(Utility);
object returnValue = GetItems.Invoke(utility, null);
Now I want to type cast above returnValue
in List of type Data and access the FirstName
property. 现在,我要在数据类型的列表中的
returnValue
上键入returnValue
类型转换,并访问FirstName
属性。
How can I achieve this using reflection? 如何使用反射实现此目的?
Assuming that everything you wrote works then 假设您编写的所有内容都可以正常工作
object returnValue = GetItems.Invoke(utility, null);
returnValue
is actually a List<Data>
, but you can't cast it, because at compile time the compiler doesn't have the type information of the Data
class. returnValue
实际上是一个List<Data>
,但是您不能进行强制转换,因为在编译时,编译器没有Data
类的类型信息。 But since a List<T>
implements IList
you can cast to that and iterate over its items ( IEnumerable<object>
should work too). 但是由于
List<T>
实现了IList
您可以将其强制转换并对其项进行迭代( IEnumerable<object>
应起作用)。
Then you can use reflection again to access the FirstName
property: 然后,您可以再次使用反射来访问
FirstName
属性:
var returnValue = (IList)GetItems.Invoke(utility, null);
foreach (var item in returnValue)
{
var type = item.GetType();
var property = type.GetProperty("FirstName");
var firstName = property.GetValue(item);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.