C#过滤器怎么获取方法的参数
时间: 2024-05-13 13:19:52 浏览: 15
你可以使用反射来获取方法的参数。以下是一个示例代码:
```csharp
using System;
using System.Reflection;
class Program
{
static void Main(string[] args)
{
MethodInfo methodInfo = typeof(Program).GetMethod("MyMethod");
ParameterInfo[] parameters = methodInfo.GetParameters();
foreach (ParameterInfo parameter in parameters)
{
Console.WriteLine(parameter.Name + " : " + parameter.ParameterType);
}
}
static void MyMethod(int x, string y)
{
Console.WriteLine("MyMethod called with x = " + x + " and y = " + y);
}
}
```
在上面的示例代码中,我们使用 `typeof` 运算符和 `GetMethod` 方法来获取 `MyMethod` 方法的 `MethodInfo` 对象。然后,我们使用 `GetParameters` 方法来获取方法的参数的 `ParameterInfo` 对象数组。最后,我们遍历该数组并输出参数的名称和类型。
上述代码的输出结果为:
```
x : System.Int32
y : System.String
```
这表示 `MyMethod` 方法有两个参数,一个是 `int` 类型的 `x`,另一个是 `string` 类型的 `y`。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)