Home >Backend Development >C++ >Can `TryParse` Be Used for Generic Type Validation in C#?
Extending Generic Type Validation with 'TryParse'
With the intent of verifying whether a given string adheres to a predefined type, an attempt is being made to develop a generic extension utilizing 'TryParse'. However, this effort has encountered a compilation obstacle as 'TryParse' remains unresolved.
The crux of this issue lies in the fact that 'TryParse' is not encapsulated within any recognizable interface. Hence, the question arises as to the feasibility of such an implementation.
One potential solution involves leveraging the TypeDescriptor class, a mechanism designed specifically for this purpose. By incorporating this class, a more robust approach can be adopted:
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); } }
This updated approach boasts several advantages:
Ultimately, this revised solution effectively addresses the initial challenge, providing a means to ascertain the validity of a given input string against a predefined type.
The above is the detailed content of Can `TryParse` Be Used for Generic Type Validation in C#?. For more information, please follow other related articles on the PHP Chinese website!