我可以检查的格式说明适用于特定的数据类型?适用于、数据类型、格式

2023-09-03 20:45:01 作者:现在唯美诗意类

如果我有(在.NET / C#)的实例类型的变量我可以将其转换为像一个格式化字符串:

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

问:有没有一种方法来检查的格式说明是有效的(除了试图格式化和捕捉异常)之前,我申请的格式,像 long.IsFormatValid(Q10)

感谢您的帮助!

推荐答案

我还没有试过,但我想你可以创建一个扩展方法,如:

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