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

北城以北 提交于 2019-12-22 08:37:34

问题


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 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!


回答1:


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")) 
{
    ...



回答2:


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.



来源:https://stackoverflow.com/questions/4408540/can-i-check-if-a-format-specifier-is-valid-for-a-given-data-type

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!