c# - C#中ParameterInfo的数据类型是什么?
问题描述
我有一个代码可以获取包含类方法及其参数的类的元数据。然后将检测到的 ParameterInfo 传递给另一个方法,以根据每个参数数据类型进行一些其他操作。以下是我提出问题的伪代码片段:
static void TypeDetector (ParameterInfo p) {
switch (p.ParameterType)
{
case System.Int32:
do_something;
break;
case System.String:
do_something;
break;
default:
do_nothing;
break;
}
但我收到这些编译错误消息:
error CS0119: 'int' is a type, which is not valid in the given context (this error refers to case System.Int32)
error CS0119: 'string' is a type, which is not valid in the given context (and this error refers to case System.String)
我还将“TypeDetector”方法参数从 ParameterInfo 更改为 Type,但我收到:
'Type' does not contain a definition for 'ParameterType' and no accessible extension method 'ParameterType' accepting a first argument of type 'Type' could be found
后一个错误消息是有道理的,因为我认为我应该使用 ParameterInfo 作为“TypeDetector”参数。我想知道我的方法应该改变什么?
谢谢。
解决方案
你有几个选择,没有一个是真正优雅的。
using System;
using System.Reflection;
public class C
{
public void TypeDetector(ParameterInfo p)
{
if (ReferenceEquals(p.ParameterType, typeof(int)))
{
}
else if (ReferenceEquals(p.ParameterType, typeof(string)))
{
}
else
{
}
}
public void TypeDetector_SwitchStatement(ParameterInfo p)
{
// C# 7
switch (p.ParameterType)
{
case Type t when ReferenceEquals(t, typeof(int)):
break;
case Type t when ReferenceEquals(t, typeof(string)):
break;
default:
break;
}
}
public string TypeDetector_SwitchExpression(ParameterInfo p)
{
// C# 8
return p.ParameterType switch
{
Type t when ReferenceEquals(t, typeof(int)) => "int",
Type t when ReferenceEquals(t, typeof(string)) => "string",
_ => "Something else"
};
}
}
推荐阅读
- java - Java Method.invoke 抛出 NullPointerException
- or-tools - CP_SAT:是否可以限制使用的 RAM?
- angular - 在一个角度函数中分别调用两个订阅而不混合它们
- pandas - 如何使用 pandas 将 excel 小时格式转换为分钟?
- java - 运行可运行的 jar 文件时 - 它不工作
- asterisk - 如何修复星号 1.8.18+ 编译错误?
- python - tkinter import Warning
- r - R函数将不同长度的嵌套列表转换为数据框
- google-sheets - 仅当不同列具有条件时才计算列中的唯一值
- javascript - 等待多个异步 http 请求完成