开发者

.NET - Parse data type without result

开发者 https://www.devze.com 2023-01-30 23:41 出处:网络
Is it possible to parse a data type (int, double, boolean...) in .NET without throwing an exception and without returning the result?In other words, I just want to be able to answer the question, \'Is

Is it possible to parse a data type (int, double, boolean...) in .NET without throwing an exception and without returning the result? In other words, I just want to be able to answer the question, 'Is this a valid integer?' or 'Is this a valid double?' without having to declare a result variable. I do not want to use .TryParse because I have to pass in a result variable, and I do not want to use .Parse because it will throw.

Any suggestions? (I would be surprised if this functionality wasn't present in .NET, I must be missing something.)

EDIT

Ok, this was too easy... just made a couple extension methods and I'm on my way...

    <Extension()> _
    Public Function IsValidInteger(ByVal value As String) As Boolean
        Dim result As Integer
        Return Integer.TryParse(value, result)
    End Function

    <Extension()> _
    Public Function IsValidDouble(ByVal value As String) As Boolean
        Dim result As Double
        Return Double.TryParse(value, result)
    End Function

Looks like this a duplicate question, however, in all honesty, I didn't find this one until now:

Integer.TryParse - a better way?

The accepted a开发者_如何学Pythonnswer from that question is probably better than anything suggested here.


You can use the different TryParse methods defined on the types.

This the best you can do without writing your own parser/tokenizer.


No, there is no such functionality in the framework.

The reason is that there is so little gain in only determining if a string is parsable compared to actually parsing it, that it's just not worth it to have both methods.

Almost always when you want to find out if it's possible to parse a string, you will also want to parse the string. If there was a method to just find out if it was possible to parse a string, it would frequently be misused in this way, causing the string to be parsed twice:

if (Int32.CanParse(theString)) {
  int n = Int32.Parse(theString);
}

The TryParse method does it in a single operation, and it also works in your very unusual case, with only the inconvenience of having to declare a variable for the result.


I don't think there is anything in the framework for this. As Guffa points out, the provision of such methods in the framework would be of limited use.

But if you really wanted, you could write a "convention-based" extension-method like:

public static class ParseExtensions
{
    public delegate bool TryParser<T>(string input, out T result);

    public static bool CanParseTo<T>(this string text, TryParser<T> tryParser)
    {
        if (text == null)
            throw new ArgumentNullException("text");

        if (tryParser == null)
            throw new ArgumentNullException("tryParser");

        T result;
        return tryParser(text, out result);
    }
}

Usage (it's a pity type-inference doesn't work here):

bool intTrue = "123".CanParseTo<int>(int.TryParse);
bool intFalse = "xxx".CanParseTo<int>(int.TryParse);

bool enumTrue = "Encrypted".CanParseTo<FileOptions>(Enum.TryParse<FileOptions>);
bool enumFalse = "xxx".CanParseTo<FileOptions>(Enum.TryParse<FileOptions>);

bool dateTimeTrue = "2004/05/05".CanParseTo<DateTime>(DateTime.TryParse);
bool dateTimeFalse = "xxx".CanParseTo<DateTime>(DateTime.TryParse);


Yes make your own extension methods for that, the methods aren't present because it's not something that people use everyday . . .

public bool IsValidInt(this int someInt, string toCheck) { int dontNeed; return Int.TryParse(toCheck, out dontNeed); }


You could write yourself an extension method that will do the job for you more conveniently than using TryParse every time, if you just want to avoid that. Something like:

public static bool IsValidDateFormat(this string s)
{
    DateTime dt;
    return DateTime.TryParse(s, out dt);
}

(There may be a slightly more elegant way to do it, I just threw this together to be compilable.)


Try this function below:

public bool isValid<T>(object t)
{
    try
    {
        Convert.ChangeType(t, typeof(T));
        return true;
    }
    catch(Exception e)
    {
        return false;
    }
}

You needn't to write an extension for every basic types combinations because this method is generic. Example:

bool isValidInt = isValid<int>("t14");
//isValidInt == false
bool isValidInt2 = isValid<int>("144");
//isValidInt2 == true
0

精彩评论

暂无评论...
验证码 换一张
取 消