.Net Standard 1.6 中的 TypeConverter 替代方案

TypeConverter alternative in .Net Standard 1.6

我正在我的项目中使用反射。

在某些情况下,我需要 cast/convert 将我从网页源检索到的字符串转换为其他类型,如 int 等

我用这个签名创建了方法:

internal static T GetData<T>(parameter,parameter)

因此,如果框架用户想要获取 int ,请轻松使用 GetData<int>

我想在我的方法中添加异常处理 而不是 try/catch

用于检查 String 是否可以转换为 T。

问题是 TypeConverter class 在 .NetStandard 中不可用。

    TypeConverter typeConverter = TypeDescriptor.GetConverter(typeof(string));

    if (typeConverter.CanConvertTo(typeof(T)) == false)
    {
        throw new InvalidCastException("Can not convert");
    }

我想检查转换,使用 .Net 的本机功能,而不是使用第三方库或 try/catch。 我该怎么做?

一个简单的选择是更新到 .NET Standard 2.0:

我创建了这个扩展方法。

模拟TypeConverter.

也许是疯了或者……? 但对我有用。

我很高兴听到您对此解决方案的意见以及更好的想法或对该方法的补充。

        internal static bool CanConvertTo(this Type originType, Type destinationType)
        {
            if (originType == null)
            {
                throw new ArgumentNullException("parameter originType is null");
            }

            if (destinationType == null)
            {
                throw new ArgumentNullException("parameter destinationType is null");
            }


#if !(NETSTANDARD1_3 || NETSTANDARD1_6)
            TypeConverter typeConverter = TypeDescriptor.GetConverter(originType);

            if (typeConverter.CanConvertTo(destinationType) == false)
            {
                return false;
            }
#endif


#if NETSTANDARD1_3 || NETSTANDARD1_6
            try
            {
                object tester;
                tester = Convert.ChangeType(originType,destinationType);
            }
            catch
            {
                return false;
            }
#endif

            return true;
        }