开发者

How can I override TryParse?

开发者 https://www.devze.com 2023-01-02 23:13 出处:网络
I would like to override bool\'s TryParse method to accept \"yes\" and \"no.\" I know the method I want to us开发者_C百科e (below) but I don\'t know how to override bool\'s method.

I would like to override bool's TryParse method to accept "yes" and "no." I know the method I want to us开发者_C百科e (below) but I don't know how to override bool's method.

... bool TryParse(string value, out bool result)
{
    if (value == "yes")
    {
        result = true;
        return true;
    }
    else if (value == "no")
    {
        result = false;
        return true;
    }
    else
    {
        return bool.TryParse(value, result);
    }
}


You can't override a static method. You could however create an extension method.

public static bool TryParse(this string value, out bool result)
{
    // For a case-insensitive compare, I recommend using
    // "yes".Equals(value, StringComparison.OrdinalIgnoreCase); 
    if (value == "yes")
    {
        result = true;
        return true;
    }
    if (value == "no")
    {
        result = false;
        return true;
    }

    return bool.TryParse(value, out result);
}

Put this in a static class, and call your code like this:

string a = "yes";
bool isTrue;
bool canParse = a.TryParse(out isTrue);


TryParse is a static method. You can't override a static method.


TryParse is a static method and you can't override static methods.

You could always try to create an extension method for strings to do what you want:

public static bool ParseYesNo(this string str, out bool val)
{
    if(str.ToLowerInvariant() == "yes")
    {
        val = true;
        return true;
    }
    else if (str.ToLowerInvariant() == "no")
    {
        val = false;
        return true;
    }

    return bool.TryParse(str, out val);
}


You cannot override TryParse. However, you could create an extension method on string for convenience.

public static class StringExtension
{
    public static bool TryParseToBoolean(this string value, bool acceptYesNo, out bool result)
    {
        if (acceptYesNo)
        {
            string upper = value.ToUpper();
            if (upper == "YES")
            {
                result = true;
                return true;
            }
            if (upper == "NO")
            {
                result = false;
                return true;
            }
        }
        return bool.TryParse(value, out result);
    }
}

And then it would be used like so:

public static class Program
{
    public static void Main(string[] args)
    {
        bool result;
        string value = "yes";
        if (value.TryParseToBoolean(true, out result))
        {
            Console.WriteLine("good input");
        }
        else
        {
            Console.WriteLine("bad input");
        }
    }
}


This is not possible.

0

精彩评论

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