我可以检查的格式说明适用于特定的数据类型? [英] Can I check if a format specifier is valid for a given data type?
本文介绍了我可以检查的格式说明适用于特定的数据类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有(在.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"))
{
...
这篇关于我可以检查的格式说明适用于特定的数据类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文