c sharp 反射方法 返回ienumerable<T>
时间: 2023-12-12 20:02:51 浏览: 139
以下是一个示例代码,演示如何使用反射来返回IEnumerable<T>:
```c#
using System;
using System.Collections.Generic;
using System.Reflection;
public class MyClass
{
public IEnumerable<int> MyMethod()
{
yield return 1;
yield return 2;
yield return 3;
}
}
class Program
{
static void Main(string[] args)
{
MyClass obj = new MyClass();
MethodInfo method = typeof(MyClass).GetMethod("MyMethod");
var enumerable = method.Invoke(obj, null) as IEnumerable<int>;
foreach (int i in enumerable)
{
Console.WriteLine(i);
}
}
}
```
在此示例中,我们创建了一个名为MyClass的类,并在其中定义了一个返回IEnumerable<int>的方法MyMethod。然后,我们使用反射获取该方法的MethodInfo对象,并使用Invoke方法调用该方法。Invoke方法返回一个object类型的结果,我们将其转换为IEnumerable<int>类型,并使用foreach循环遍历结果集并输出每个元素的值。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)