c# - 将变量转换为仅在运行时已知的类型?

标签 c#

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].ParameterType;
        value = (string)method.Invoke(null, new[] { value });
    }
}

如何将 value 转换为 paramTypevalue 是一个 stringparamType 可能只是一个基本类型,如 intstring,或者 float。如果无法进行转换,我很乐意抛出异常。

最佳答案

您使用的类型都实现了 IConvertible。因此,您可以使用 ChangeType

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

关于c# - 将变量转换为仅在运行时已知的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4010144/

相关文章:

c# - 如何在 where 子句内的可枚举条件上使用 if 条件

c# - 非公共(public)事件的 EventInfo.AddEventHandler 的替代方法

c# - Kendo Treeview 和阅读网址

c# - 将字节数组复制到剪贴板

c# - System.Math.Abs​​() 调用 native 方法 System.AppDomain.GetId()?

c# - 在 DatagridViewCell 中显示用户控件

c# - SQLite: 'Unable to open the database file' 异常与多个命令的事务

c# - 暂停/恢复定时器的问题

c# - 如何为 DateTime 验证添加范围

c# - 使用 AAD 对 Azure API 应用程序进行身份验证时出现 401 错误