如何通过反射+泛型实现静态Convert类的多类型十进制转二进制功能
问题原因
Ambiguous match found报错的核心原因是Convert类存在多个名为ToString的重载方法,直接调用无参数过滤的GetMethod("ToString")时,反射无法定位到你需要的、接收「数值类型+进制参数」的重载。
解决方案
调用GetMethod时显式传入需要匹配的参数类型数组,指定第一个参数为泛型T的类型,第二个参数为进制对应的int类型,即可精准定位到对应的重载。
基础实现
public static string DecToBinary<T>(T number) where T : struct, IComparable, IFormattable, IConvertible { // 显式指定要查找的重载参数类型:第一个为T类型,第二个为int类型的进制参数 var toStringMethod = typeof(Convert).GetMethod("ToString", new Type[] { typeof(T), typeof(int) }); if (toStringMethod == null) { throw new NotSupportedException($"不支持类型 {typeof(T).Name} 的十进制转二进制操作"); } return (string)toStringMethod.Invoke(null, new object[] { number, 2 }); }
性能优化版本(带方法缓存)
如果频繁调用该方法,可以添加静态缓存存储不同类型对应的ToString方法实例,避免每次调用都重复执行反射查找:
using System.Collections.Concurrent; private static readonly ConcurrentDictionary<Type, MethodInfo> _toStringMethodCache = new ConcurrentDictionary<Type, MethodInfo>(); public static string DecToBinary<T>(T number) where T : struct, IComparable, IFormattable, IConvertible { Type targetType = typeof(T); if (!_toStringMethodCache.TryGetValue(targetType, out var toStringMethod)) { toStringMethod = typeof(Convert).GetMethod("ToString", new Type[] { targetType, typeof(int) }); if (toStringMethod == null) { throw new NotSupportedException($"不支持类型 {targetType.Name} 的十进制转二进制操作"); } _toStringMethodCache.TryAdd(targetType, toStringMethod); } return (string)toStringMethod.Invoke(null, new object[] { number, 2 }); }
测试示例
// 覆盖多种数值类型测试 Console.WriteLine(DecToBinary((byte)12)); // 输出:1100 Console.WriteLine(DecToBinary((short)123)); // 输出:1111011 Console.WriteLine(DecToBinary(1234)); // 输出:10011010010 Console.WriteLine(DecToBinary(123456789L)); // 输出:111010110111100110100010101
内容的提问来源于stack exchange,提问作者Francisco Cardão
相关产品推荐
相关产品推荐

