通用泛型类型从字符串转换 [英] Universal generic type conversion from string

查看:132
本文介绍了通用泛型类型从字符串转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的任务是编写一个方法StringToType(),它将字符串转换为指定的类型T.

My task is to write a method StringToType() that converts a string to the specified type T.


  1. 对于基本类型,I使用方法Convert.ChangeType()

  2. 对于枚举类型 - Enum.TryParse()

  3. 对于所有其他自定义类型,我创建了一个接口包含方法FromString()的IConvertibleFromString将字符串转换为指定的类型。任何需要从字符串转换的类都必须实现此接口。
  1. For primitive types, I use the method Convert.ChangeType()
  2. For enum-types - Enum.TryParse()
  3. For all other custom types, I created an interface "IConvertibleFromString" that contains a method "FromString()" to convert the string to the specified type. Any class that will need to convert from string must implement this interface.

但我不喜欢我实现方法StringToType() 。我希望使用不到反射并尽可能保证性能。

But me do not like the way I implemented method StringToType(). I would like to use less than the reflection and ensure as much as possible the performance.

请告知如何最好地实施/更改它。

Please advise how best to implement/change it.

class Program
{
    static bool StringToType<T>(string str, ref T value)
    {
        Type typeT = typeof(T);
        bool isSuccess = false;
        if (typeT.GetInterface("IConvertibleFromString") != null)
        {
            return (bool)typeT.GetMethod("FromString").Invoke(value, new object[] { str });
        }
        else if (typeT.IsEnum)
        {
            MethodInfo methodTryParse = typeT.GetMethod("TryParse").MakeGenericMethod(typeT);
            return (bool)methodTryParse.Invoke(null, new object[] { str, value });
        }
        else if (typeT.IsPrimitive)
        {
            value = (T)Convert.ChangeType(str, typeT);
            return true;
        }
        return isSuccess;
    }

    static void Main(string[] args)
    {
        string intStr = "23";
        int val1 = 0;
        bool res = StringToType<int>(intStr, ref val1);
        Class1 c1;
        res = StringToType<Class1>(intStr, ref c1);
        Console.ReadKey();
    }
}

interface IConvertibleFromString
{
    bool FromString(string str);
}

class MySomeClass : IConvertibleFromString
{
    int someVal;

    public bool FromString(string str)
    {
        return int.TryParse(str, out someVal);
    }
}


推荐答案

似乎对我来说表现最好。向各种消费者投入了一百万次迭代。

This seemed to perform the best for me. Threw a million iterations at it with various consumers. It's a combination of folks' comments, with a little extra.

    static Boolean TryParseString<T>(
        String stringValue, ref T value)
    {

        Type typeT = typeof(T);

        if (typeT.IsPrimitive)
        {
            value = (T)Convert.ChangeType(stringValue, typeT);
            return true;
        }
        else if (typeT.IsEnum)
        {
            value = (T)System.Enum.Parse(typeT, stringValue); // Yeah, we're making an assumption
            return true;
        }
        else
        {
            var convertible = value as IConvertible;
            if (convertible != null)
            {
                return convertible.FromString(stringValue);
            }
        }

        return false;

    }

这篇关于通用泛型类型从字符串转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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