首页 > 解决方案 > 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”参数。我想知道我的方法应该改变什么?

谢谢。

标签: c#

解决方案


你有几个选择,没有一个是真正优雅的。

在 Sharplab 上编辑

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"
        };
    }
}

推荐阅读