开发者

Can I check if a format specifier is valid for a given data type?

开发者 https://www.devze.com 2023-01-29 16:41 出处:网络
If I have (in .NET/C#) for instance a variable of type long I can convert it to a formatted string like:

If I have (in .NET/C#) for instance a variable of type long I can convert it to a formatted string like:

long value = 12345;
string formattedValue = value.ToString("D10"); // returns "0000012345"

If I specify a format which isn't valid for that type I get an exception:

long value = 12345;
string formattedValue = value.ToString("Q10"); // throws a System.FormatException

Question: Is there a way开发者_JS百科 to check if a format specifier is valid (aside from trying to format and catching the exception) before I apply that format, something like long.IsFormatValid("Q10")?

Thanks for help!


I've not tried this but I would think you could create an extension method such as:

namespace ExtensionMethods
{
    public static class MyExtensions
    {

        public static bool IsFormatValid<T>(this T target, string Format)
            where T : IFormattable
        {
            try
            {
                target.ToString(Format, null);
            }
            catch
            {
                return false;
            }  
            return true;
        }
    }
}

which you could then apply thus:

long value = 12345;
if (value.IsFormatValid("Q0")) 
{
    ...


Rather than creating a check for that I'd suggest that it might be better that the developers reads the documentation to find out what's allowed where.

However, if there is a problem with a lot of typos being made, I suppose you could write a lookup table from the information on that page. Though that could just give you a false sense of security in that you'd get people making mistakes between valid format specifiers (writing an f but they meant e etc).

Edited to remove confused bit about TryParse/Parse.

0

精彩评论

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