繁体   English   中英

在 C# 中调用使用反射的方法时如何对参数进行自动类型转换?

[英]How to do automatic type conversion for parameters when invoking a method using reflection in C#?

我需要使用 C# 通过反射调用类型的方法。

在运行时,我的数据将包含一个包含名称/值对的字典。 Dictionary 中的名称将对应于我将调用的方法上的参数名称。 此外,在运行时,我将拥有一个任意的程序集限定类型名称和一个方法名称。 在设计时,我不知道类型和方法,除了该方法将接受可变数量的 int、string、DateTime、bool、int[]、string[]、DateTime[] 或 bool 类型的参数[]。

我可以毫无问题地使用反射创建该类型的实例并调用该方法。 我被困在我必须将字典中的字符串值转换为调用时方法所需的适当类型的地步:

someMethodInfo.Invoke(instance, new [] { ... })

我知道我可能需要通过 MethodInfo.GetParameters() 枚举并为每个参数执行类型转换。 我想弄清楚的是如何做到这一点,理想情况下,如何有效地做到这一点。

到目前为止,我的研究涉及深入研究 MVC 源代码,因为它在将表单值传递给 ActionMethod 时做了类似的事情。 我找到了ActionMethodDispatcher ,但它使用了我不熟悉的 LINQ 表达式。

我还查看了关于 SO 的类似问题,但没有找到任何可以回答我问题的内容。

我欢迎任何指向解决方案的指针。

下面是一些可用于参数转换的代码:

public object ConvertSingleItem(string value, Type newType)
{
    if (typeof(IConvertible).IsAssignableFrom(newType))
    {
        return Convert.ChangeType(value, newType);
    }
    else
    {
        // TODO: Add custom conversion for non IConvertible types
        var converter = CustomConvertersFactory.GetConverter(newType);
        return converter.Convert(value);
    }
}

public object ConvertStringToNewNonNullableType(string value, Type newType)
{
    // Do conversion form string to array - not sure how array will be stored in string
    if (newType.IsArray)
    {
        // For comma separated list
        Type singleItemType = newType.GetElementType();

        var elements = new ArrayList();
        foreach (var element in value.Split(','))
        {
            var convertedSingleItem = ConvertSingleItem(element, singleItemType);
            elements.Add(convertedSingleItem);
        }
        return elements.ToArray(singleItemType);
    }
    return ConvertSingleItem(value, newType);
}

public object ConvertStringToNewType(string value, Type newType)
{
    // If it's not a nullable type, just pass through the parameters to Convert.ChangeType
    if (newType.IsGenericType && newType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
    {
        if (value == null)
        {
            return null;
        }
        return ConvertStringToNewNonNullableType(value, new NullableConverter(newType).UnderlyingType);
    }
    return ConvertStringToNewNonNullableType(value, newType);
}

public object CallMethod(object instance, MethodInfo methodInfo, Dictionary<string, string> parameters)
{
    var methodParameters = methodInfo.GetParameters();

    var parametersForInvocation = new List<object>();
    foreach (var methodParameter in methodParameters)
    {
        string value;
        if (parameters.TryGetValue(methodParameter.Name, out value))
        {
            var convertedValue = ConvertStringToNewType(value, methodParameter.ParameterType);
            parametersForInvocation.Add(convertedValue);
        }
        else
        {
            // Get default value of the appropriate type or throw an exception
            var defaultValue = Activator.CreateInstance(methodParameter.ParameterType);
            parametersForInvocation.Add(defaultValue);
        }
    }
    return methodInfo.Invoke(instance, parametersForInvocation.ToArray());
}

它支持原始类型、Nullables 和原始类型的 Arrays。 如果您要使用不支持 IConvertible 接口的类型 - 最好为每个单独的类型实现自定义转换器。

它可以用 Linq 以更优雅的方式编写。

活力

您要转换的值应该是 object,否则标准类型之外的转换将不起作用。 您可以轻松地在类型之间进行转换,如下所示:

object value = false; // false
Type chType = typeof(String); // System.String
object newValue = Convert.ChangeType(value, chType); // "false"

就这么简单。 如果你想要一个方法:

public object ConvertType(object value, Type conversionType)
{
    //Check if type is Nullable
    if (conversionType.IsGenericType &&
        conversionType.GetGenericTypeDefinition() == typeof(Nullable<>))
    {
        //If the type is Nullable and the value is null
        //Just return null
        if (value == null)
        {
            return null;
        }

        //Type is Nullable and we have a value, override conversion type to underlying
        //type for the Nullable to avoid exception in Convert.ChangeType
        var nullableConverter = new NullableConverter(conversionType);
        conversionType = nullableConverter.UnderlyingType;
    }

    return Convert.ChangeType(value, conversionType);
}

也许管理“转换器”的一个好方法是维护一个Dictionary<Type, IMyTypeConverter> - 其中IMyTypeConverter有一个object Convert(string value)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM