Dynamic TryParse for all data types

后端 未结 3 517
小蘑菇
小蘑菇 2020-12-21 06:39

I have the need to examine to see if an object can be converted to a specific DataType or not, and came up with this :

public static bool TryParseAll(System         


        
3条回答
  •  长情又很酷
    2020-12-21 07:18

    Here is my version of generic TryParse method. I believe you can use this version too:

    double pi;
    if(ValueTypeHelper.TryParse("3.14159", out pi)) {
        // .. pi = 3.14159
    }
    ...
    string eStr = "2.71828";
    float e;
    if(eStr.TryParse(out e)) {
        // .. e = 2.71828f
    }
    ...
    static class ValueTypeHelper {
        static IDictionary cache = new Dictionary();
        public static bool TryParse(this string valueStr, out T result) {
            Delegate d = null;
            if(!cache.TryGetValue(typeof(T), out d)) {
                var mInfos = typeof(T).GetMember("TryParse", MemberTypes.Method, BindingFlags.Static | BindingFlags.Public);
                if(mInfos.Length > 0) {
                    var s = Expression.Parameter(typeof(string));
                    var r = Expression.Parameter(typeof(T).MakeByRefType());
                    d = Expression.Lambda>(
                        Expression.Call(mInfos[0] as MethodInfo, s, r), s, r).Compile();
                }
                cache.Add(typeof(T), d);
            }
            result = default(T);
            TryParseDelegate tryParse = d as TryParseDelegate;
            return (tryParse != null) && tryParse(valueStr, out result);
        }
        delegate bool TryParseDelegate(string valueStr, out T result);
    }
    

提交回复
热议问题