转换变量在运行时类型才知道? [英] Convert variable to type only known at run-time?

查看:110
本文介绍了转换变量在运行时类型才知道?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

foreach (var filter in filters)
{
    var filterType = typeof(Filters);
    var method = filterType.GetMethod(filter, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Static);
    if (method != null)
    {
        var parameters = method.GetParameters();
        Type paramType = parameters[0].GetType();
        value = (string)method.Invoke(null, new[] { value });
    }
}

我怎么能投 paramType 字符串 paramType 将可能只是一个基本型如 INT 字符串,或者浮动。我冷静了,如果无法转换,它抛出一个异常。

How can I cast value to paramType? value is a string, paramType will probably just be a basic type like int, string, or maybe float. I'm cool with it throwing an exception if no conversion is possible.

推荐答案

所有正在使用的实现的类型 IConvertible 。因此,你可以使用的changetype

The types you are using all implement IConvertible. As such you can use ChangeType.

 value = Convert.ChangeType(method.Invoke(null, new[] { value }), paramType);

这篇关于转换变量在运行时类型才知道?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆