In an attempt to create a generic extension method for verifying string values, you encountered an issue with 'TryParse' not being defined in any interface and sought an alternative solution.
Alternative Approach Using TypeDescriptor
The TypeDescriptor class provides a way to retrieve a type converter for a given data type. This converter can be used to convert strings to and from other types. Here's an updated version of your code:
public static bool Is(this string input, Type targetType) { try { TypeDescriptor.GetConverter(targetType).ConvertFromString(input); return true; } catch { return false; } }
In this version, you can pass any target type, and it will attempt to convert the string to that type using the appropriate converter. If the conversion succeeds, the method returns true; otherwise, it returns false.
Exceptions and Alternatives
While the exception-based approach works, you may prefer a more robust option. Instead of using exceptions, you could return a Nullable
Alternatively, you could create overloads for common types, such as int, double, and DateTime, and define custom logic for each type. This would eliminate the need for a generic implementation and provide more efficient and type-safe conversions.
The above is the detailed content of How Can I Generically Test if a String Can Be Parsed to a Specific Type?. For more information, please follow other related articles on the PHP Chinese website!