Home > Backend Development > C++ > Can Generic String Validation Be Achieved Using TryParse?

Can Generic String Validation Be Achieved Using TryParse?

Susan Sarandon
Release: 2025-01-03 02:24:42
Original
507 people have browsed it

Can Generic String Validation Be Achieved Using TryParse?

Generic String Conversion with TryParse

In an attempt to create a generic extension that utilizes 'TryParse' to validate strings against specific types, the following code was encountered:

public static bool Is<T>(this string input)
{
    T notUsed;
    return T.TryParse(input, out notUsed);
}
Copy after login

This code fails to compile due to the inability to resolve the 'TryParse' symbol. 'TryParse' is not part of any interface, posing the question of whether this functionality is achievable.

Alternative Solution using TypeDescriptor

One approach is to employ the TypeDescriptor class:

public static bool Is(this string input, Type targetType)
{
    try
    {
        TypeDescriptor.GetConverter(targetType).ConvertFromString(input);
        return true;
    }
    catch
    {
        return false;
    }
}
Copy after login

This method passes the target type explicitly, avoiding the use of generics and allowing for runtime type conversion. TypeDescriptor provides functionality for converting strings to various types, enabling you to validate strings against desired types.

The above is the detailed content of Can Generic String Validation Be Achieved Using TryParse?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template