Generic TryParse
我正在尝试创建一个使用"typarse"检查字符串是否为给定类型的通用扩展:
1 2 3 4 5 |
这不会编译,因为它无法解析符号"typarse"
据我所知,"胰蛋白酶"不是任何接口的一部分。
这有可能吗?
更新:
使用下面的答案,我想到了:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
它工作得很好,但我认为以这种方式使用异常对我来说是不合适的。
更新2:
修改为传递类型而不是使用泛型:
1 2 3 4 5 6 7 8 9 10 11 12 | public static bool Is(this string input, Type targetType) { try { TypeDescriptor.GetConverter(targetType).ConvertFromString(input); return true; } catch { return false; } } |
您应该使用typescriptor类:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | public static T Convert<T>(this string input) { try { var converter = TypeDescriptor.GetConverter(typeof(T)); if(converter != null) { // Cast ConvertFromString(string text) : object to (T) return (T)converter.ConvertFromString(input); } return default(T); } catch (NotSupportedException) { return default(T); } } |
我最近还需要一个普通的胰蛋白酶。这就是我的想法;
1 2 3 4 5 6 7 8 9 10 11 12 | public static T? TryParse<T>(string value, TryParseHandler<T> handler) where T : struct { if (String.IsNullOrEmpty(value)) return null; T result; if (handler(value, out result)) return result; Trace.TraceWarning("Invalid value '{0}'", value); return null; } public delegate bool TryParseHandler<T>(string value, out T result); |
那么这只是一个打电话给Thusly的问题:
1 2 | var value = TryParse<int>("123", int.TryParse); var value2 = TryParse<decimal>("123.123", decimal.TryParse); |
使用try/catch进行流控制是一个糟糕的策略。当运行时处理异常时,引发异常会导致性能滞后。而是在转换前验证数据。
1 2 3 4 5 6 7 | var attemptedValue ="asdfasdsd"; var type = typeof(int); var converter = TypeDescriptor.GetConverter(type); if (converter != null && converter.IsValid(attemptedValue)) return converter.ConvertFromString(attemptedValue); else return Activator.CreateInstance(type); |
如果设置为使用台盼色,则可以使用反射并按如下方式执行:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
对于每个泛型类型,它都使用静态构造函数,因此在第一次对给定类型调用它时,它只需要做昂贵的工作。它处理系统名称空间中所有具有typarse方法的类型。它还可以处理除枚举之外的每个(结构)的可空版本。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 | public static bool TryParse<t>(this string Value, out t result) { return TryParser<t>.TryParse(Value.SafeTrim(), out result); } private delegate bool TryParseDelegate<t>(string value, out t result); private static class TryParser<T> { private static TryParseDelegate<T> parser; // Static constructor: static TryParser() { Type t = typeof(T); if (t.IsEnum) AssignClass<T>(GetEnumTryParse<T>()); else if (t == typeof(bool) || t == typeof(bool?)) AssignStruct<bool>(bool.TryParse); else if (t == typeof(byte) || t == typeof(byte?)) AssignStruct<byte>(byte.TryParse); else if (t == typeof(short) || t == typeof(short?)) AssignStruct<short>(short.TryParse); else if (t == typeof(char) || t == typeof(char?)) AssignStruct<char>(char.TryParse); else if (t == typeof(int) || t == typeof(int?)) AssignStruct<int>(int.TryParse); else if (t == typeof(long) || t == typeof(long?)) AssignStruct<long>(long.TryParse); else if (t == typeof(sbyte) || t == typeof(sbyte?)) AssignStruct<sbyte>(sbyte.TryParse); else if (t == typeof(ushort) || t == typeof(ushort?)) AssignStruct<ushort>(ushort.TryParse); else if (t == typeof(uint) || t == typeof(uint?)) AssignStruct<uint>(uint.TryParse); else if (t == typeof(ulong) || t == typeof(ulong?)) AssignStruct<ulong>(ulong.TryParse); else if (t == typeof(decimal) || t == typeof(decimal?)) AssignStruct<decimal>(decimal.TryParse); else if (t == typeof(float) || t == typeof(float?)) AssignStruct<float>(float.TryParse); else if (t == typeof(double) || t == typeof(double?)) AssignStruct<double>(double.TryParse); else if (t == typeof(DateTime) || t == typeof(DateTime?)) AssignStruct<DateTime>(DateTime.TryParse); else if (t == typeof(TimeSpan) || t == typeof(TimeSpan?)) AssignStruct<TimeSpan>(TimeSpan.TryParse); else if (t == typeof(Guid) || t == typeof(Guid?)) AssignStruct<Guid>(Guid.TryParse); else if (t == typeof(Version)) AssignClass<Version>(Version.TryParse); } private static void AssignStruct<t>(TryParseDelegate<t> del) where t: struct { TryParser<t>.parser = del; if (typeof(t).IsGenericType && typeof(t).GetGenericTypeDefinition() == typeof(Nullable<>)) { return; } AssignClass<t?>(TryParseNullable<t>); } private static void AssignClass<t>(TryParseDelegate<t> del) { TryParser<t>.parser = del; } public static bool TryParse(string Value, out T Result) { if (parser == null) { Result = default(T); return false; } return parser(Value, out Result); } } private static bool TryParseEnum<t>(this string Value, out t result) { try { object temp = Enum.Parse(typeof(t), Value, true); if (temp is t) { result = (t)temp; return true; } } catch { } result = default(t); return false; } private static MethodInfo EnumTryParseMethod; private static TryParseDelegate<t> GetEnumTryParse<t>() { Type type = typeof(t); if (EnumTryParseMethod == null) { var methods = typeof(Enum).GetMethods( BindingFlags.Public | BindingFlags.Static); foreach (var method in methods) if (method.Name =="TryParse" && method.IsGenericMethodDefinition && method.GetParameters().Length == 2 && method.GetParameters()[0].ParameterType == typeof(string)) { EnumTryParseMethod = method; break; } } var result = Delegate.CreateDelegate( typeof(TryParseDelegate<t>), EnumTryParseMethod.MakeGenericMethod(type), false) as TryParseDelegate<t>; if (result == null) return TryParseEnum<t>; else return result; } private static bool TryParseNullable<t>(string Value, out t? Result) where t: struct { t temp; if (TryParser<t>.TryParse(Value, out temp)) { Result = temp; return true; } else { Result = null; return false; } } |
您不能在常规类型上执行此操作。
您可以做的是创建一个ITryParsable接口,并将其用于实现此接口的自定义类型。
不过,我想您打算将它用于基本类型,如
像这样的怎么样?
http://madskristensen.net/post/universal-data-type-checker.aspx(存档)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | /// <summary> /// Checks the specified value to see if it can be /// converted into the specified type. /// <remarks> /// The method supports all the primitive types of the CLR /// such as int, boolean, double, guid etc. as well as other /// simple types like Color and Unit and custom enum types. /// </remarks> /// </summary> /// <param name="value">The value to check.</param> /// <param name="type">The type that the value will be checked against.</param> /// <returns>True if the value can convert to the given type, otherwise false. </returns> public static bool CanConvert(string value, Type type) { if (string.IsNullOrEmpty(value) || type == null) return false; System.ComponentModel.TypeConverter conv = System.ComponentModel.TypeDescriptor.GetConverter(type); if (conv.CanConvertFrom(typeof(string))) { try { conv.ConvertFrom(value); return true; } catch { } } return false; } |
这可以很容易地转换为通用方法。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
在Charlie Brown发布的解决方案的启发下,我使用反射创建了一个通用的类胰蛋白酶,它可以选择输出解析的值:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | /// <summary> /// Tries to convert the specified string representation of a logical value to /// its type T equivalent. A return value indicates whether the conversion /// succeeded or failed. /// </summary> /// <typeparam name="T">The type to try and convert to.</typeparam> /// <param name="value">A string containing the value to try and convert.</param> /// <param name="result">If the conversion was successful, the converted value of type T.</param> /// <returns>If value was converted successfully, true; otherwise false.</returns> public static bool TryParse<T>(string value, out T result) where T : struct { var tryParseMethod = typeof(T).GetMethod("TryParse", BindingFlags.Static | BindingFlags.Public, null, new [] { typeof(string), typeof(T).MakeByRefType() }, null); var parameters = new object[] { value, null }; var retVal = (bool)tryParseMethod.Invoke(null, parameters); result = (T)parameters[1]; return retVal; } /// <summary> /// Tries to convert the specified string representation of a logical value to /// its type T equivalent. A return value indicates whether the conversion /// succeeded or failed. /// </summary> /// <typeparam name="T">The type to try and convert to.</typeparam> /// <param name="value">A string containing the value to try and convert.</param> /// <returns>If value was converted successfully, true; otherwise false.</returns> public static bool TryParse<T>(string value) where T : struct { T throwaway; var retVal = TryParse(value, out throwaway); return retVal; } |
可以这样称呼:
1 2 3 4 5 | string input ="123"; decimal myDecimal; bool myIntSuccess = TryParse<int>(input); bool myDecimalSuccess = TryParse<decimal>(input, out myDecimal); |
更新:另外,由于YotaxP的解决方案我非常喜欢,我创建了一个版本,它不使用扩展方法,但仍然有一个单例,最小化了进行反射的需要:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | /// <summary> /// Provides some extra parsing functionality for value types. /// </summary> /// <typeparam name="T">The value type T to operate on.</typeparam> public static class TryParseHelper<T> where T : struct { private delegate bool TryParseFunc(string str, out T result); private static TryParseFunc tryParseFuncCached; private static TryParseFunc tryParseCached { get { return tryParseFuncCached ?? (tryParseFuncCached = Delegate.CreateDelegate(typeof(TryParseFunc), typeof(T),"TryParse") as TryParseFunc); } } /// <summary> /// Tries to convert the specified string representation of a logical value to /// its type T equivalent. A return value indicates whether the conversion /// succeeded or failed. /// </summary> /// <param name="value">A string containing the value to try and convert.</param> /// <param name="result">If the conversion was successful, the converted value of type T.</param> /// <returns>If value was converted successfully, true; otherwise false.</returns> public static bool TryParse(string value, out T result) { return tryParseCached(value, out result); } /// <summary> /// Tries to convert the specified string representation of a logical value to /// its type T equivalent. A return value indicates whether the conversion /// succeeded or failed. /// </summary> /// <param name="value">A string containing the value to try and convert.</param> /// <returns>If value was converted successfully, true; otherwise false.</returns> public static bool TryParse(string value) { T throwaway; return TryParse(value, out throwaway); } } |
这样称呼它:
1 2 3 4 5 | string input ="987"; decimal myDecimal; bool myIntSuccess = TryParseHelper<int>.TryParse(input); bool myDecimalSuccess = TryParseHelper<decimal>.TryParse(input, out myDecimal); |
这是另一个选择。
我编写了一个类,使注册任意数量的
1 2 3 4 5 6 7 8 9 10 11 | var tp = new TryParser(); tp.Register<int>(int.TryParse); tp.Register<decimal>(decimal.TryParse); tp.Register<double>(double.TryParse); int x; if (tp.TryParse("42", out x)) { Console.WriteLine(x); }; |
我把
班级是:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | public class TryParser { public delegate bool TryParseDelegate<T>(string s, out T result); private Dictionary<Type, Delegate> _tryParsers = new Dictionary<Type, Delegate>(); public void Register<T>(TryParseDelegate<T> d) { _tryParsers[typeof(T)] = d; } public bool Deregister<T>() { return _tryParsers.Remove(typeof(T)); } public bool TryParse<T>(string s, out T result) { if (!_tryParsers.ContainsKey(typeof(T))) { throw new ArgumentException("Does not contain parser for" + typeof(T).FullName +"."); } var d = (TryParseDelegate<T>)_tryParsers[typeof(T)]; return d(s, out result); } } |
参加聚会有点晚了,但我想说的是。无异常,一次性(每种类型)反射。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | public static class Extensions { public static T? ParseAs<T>(this string str) where T : struct { T val; return GenericHelper<T>.TryParse(str, out val) ? val : default(T?); } public static T ParseAs<T>(this string str, T defaultVal) { T val; return GenericHelper<T>.TryParse(str, out val) ? val : defaultVal; } private static class GenericHelper<T> { public delegate bool TryParseFunc(string str, out T result); private static TryParseFunc tryParse; public static TryParseFunc TryParse { get { if (tryParse == null) tryParse = Delegate.CreateDelegate( typeof(TryParseFunc), typeof(T),"TryParse") as TryParseFunc; return tryParse; } } } } |
需要额外的类,因为泛型类中不允许使用扩展方法。这允许简单的使用,如下所示,并且只在第一次使用类型时命中反射。
1 | "5643".ParseAs<int>() |
这是我的尝试。我做这件事是为了"锻炼"。我试图使其与现有的"convert.tox()"-等类似,但这是一种扩展方法:
1 2 3 4 5 6 7 8 9 10 | public static bool TryParse<T>(this String str, out T parsedValue) { try { parsedValue = (T)Convert.ChangeType(str, typeof(T)); return true; } catch { parsedValue = default(T); return false; } } |
当我想做这个几乎精确的事情时,我不得不以一种艰难的方式来实现它,考虑到思考。考虑到
正如您所说,
正如@mark所说,您可以创建自己的接口并使用自定义类型,但是对于内置类型来说,您不太走运。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | public static class Primitive { public static DateTime? TryParseExact(string text, string format, IFormatProvider formatProvider = null, DateTimeStyles? style = null) { DateTime result; if (DateTime.TryParseExact(text, format, formatProvider, style ?? DateTimeStyles.None, out result)) return result; return null; } public static TResult? TryParse<TResult>(string text) where TResult : struct { TResult result; if (Delegates<TResult>.TryParse(text, out result)) return result; return null; } public static bool TryParse<TResult>(string text, out TResult result) => Delegates<TResult>.TryParse(text, out result); public static class Delegates<TResult> { private delegate bool TryParseDelegate(string text, out TResult result); private static readonly TryParseDelegate _parser = (TryParseDelegate)Delegate.CreateDelegate(typeof(TryParseDelegate), typeof(TResult),"TryParse"); public static bool TryParse(string text, out TResult result) => _parser(text, out result); } } |
在与
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | public static bool TryParse<T>(this string input, out T parsedValue) { parsedValue = default(T); try { var converter = TypeDescriptor.GetConverter(typeof(T)); parsedValue = (T)converter.ConvertFromString(input); return true; } catch (NotSupportedException) { return false; } } |
1 2 3 4 | public static T Get<T>(string val) { return (T) TypeDescriptor.GetConverter(typeof (T)).ConvertFromInvariantString(val); } |
我设法得到了这样的东西
1 2 3 4 | var result ="44".TryParse<int>(); Console.WriteLine("type={0}, value={1}, valid={2}", result.Value.GetType(), result.Value, result.IsValid ); |
这是我的密码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | public static class TryParseGeneric { //extend int public static dynamic TryParse<T>( this string input ) { dynamic runner = new StaticMembersDynamicWrapper( typeof( T ) ); T value; bool isValid = runner.TryParse( input, out value ); return new { IsValid = isValid, Value = value }; } } public class StaticMembersDynamicWrapper : DynamicObject { private readonly Type _type; public StaticMembersDynamicWrapper( Type type ) { _type = type; } // Handle static properties public override bool TryGetMember( GetMemberBinder binder, out object result ) { PropertyInfo prop = _type.GetProperty( binder.Name, BindingFlags.FlattenHierarchy | BindingFlags.Static | BindingFlags.Public ); if ( prop == null ) { result = null; return false; } result = prop.GetValue( null, null ); return true; } // Handle static methods public override bool TryInvokeMember( InvokeMemberBinder binder, object [] args, out object result ) { var methods = _type .GetMethods( BindingFlags.FlattenHierarchy | BindingFlags.Static | BindingFlags.Public ).Where( methodInfo => methodInfo.Name == binder.Name ); var method = methods.FirstOrDefault(); if ( method == null ) { result = null; return false; } result = method.Invoke( null, args ); return true; } } |
StaticMembersDynamicWrapper改编自DavidEbbo的文章(它抛出了一个含糊不清的MatchException)
这是一个"一般约束"的问题。因为您没有特定的界面,所以除非按照前面的答案的建议操作,否则您将陷入困境。
有关此方面的文档,请检查以下链接:
http://msdn.microsoft.com/en-us/library/ms379564(vs.80).aspx
它向您展示了如何使用这些约束,并应该为您提供更多的线索。
借用自http://blogs.msdn.com/b/davideb/archive/2009/10/23/using-c-dynamic-to-call-static-members.aspx
遵循此引用时:如何使用动态类型调用C 4.0中的静态方法?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 | using System; using System.Collections.Generic; using System.Dynamic; using System.Linq; using System.Reflection; namespace Utils { public class StaticMembersDynamicWrapper : DynamicObject { private Type _type; public StaticMembersDynamicWrapper(Type type) { _type = type; } // Handle static methods public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) { var methods = _type .GetMethods(BindingFlags.FlattenHierarchy | BindingFlags.Static | BindingFlags.Public) .Where(methodInfo => methodInfo.Name == binder.Name); var method = methods.FirstOrDefault(); if (method != null) { result = method.Invoke(null, args); return true; } result = null; return false; } } public static class StaticMembersDynamicWrapperExtensions { static Dictionary<Type, DynamicObject> cache = new Dictionary<Type, DynamicObject> { {typeof(double), new StaticMembersDynamicWrapper(typeof(double))}, {typeof(float), new StaticMembersDynamicWrapper(typeof(float))}, {typeof(uint), new StaticMembersDynamicWrapper(typeof(uint))}, {typeof(int), new StaticMembersDynamicWrapper(typeof(int))}, {typeof(sbyte), new StaticMembersDynamicWrapper(typeof(sbyte))} }; /// <summary> /// Allows access to static fields, properties, and methods, resolved at run-time. /// </summary> public static dynamic StaticMembers(this Type type) { DynamicObject retVal; if (!cache.TryGetValue(type, out retVal)) return new StaticMembersDynamicWrapper(type); return retVal; } } } |
使用方法如下:
1 2 3 4 5 6 7 8 9 10 11 12 | public static T? ParseNumeric<T>(this string str, bool throws = true) where T : struct { var statics = typeof(T).StaticMembers(); if (throws) return statics.Parse(str); T retval; if (!statics.TryParse(str, out retval)) return null; return retval; } |
用于从xdocument获取后代的版本。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | public static T Get<T>(XDocument xml, string descendant, T @default) { try { var converter = TypeDescriptor.GetConverter(typeof (T)); if (converter != null) { return (T) converter.ConvertFromString(xml.Descendants(descendant).Single().Value); } return @default; } catch { return @default; } } |