简单的方法来检查FormatString是否有效? [英] Easy way to check FormatString is valid?

查看:172
本文介绍了简单的方法来检查FormatString是否有效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种简单的方法来检查格式字符串是否有效?例如,以下是我们用于测试数字格式字符串的代码;

Is there an easy way to check if a format string is valid? For example the following is code that we use to test a number format string;

public static bool IsValidFormatStringNumber(string FormatString)
{
    try
    {
        const decimal number = 0.056m;
        var formattedNumber = number.ToString(FormatString);
        return formattedNumber.Length > 0;
    }
    catch
    {
        return false;
    }
}

我们正在尝试捕获异常或确定结果字符串是否没有长度.但是此测试失败,因为格式字符串"hsibbur"(任何垃圾)导致字符串"hsaibbur"具有长度.

We're trying to catch an exception or determine if the resulting string has no length. This test fails however as a format string of "hsibbur" (Any rubbish) results in a string of "hsaibbur", which has length.

我们要对百分比和日期格式字符串进行相同的测试.

We want to do the same test for Percent and Date format string.

推荐答案

如果您只想检查

If you just want to check for standard format strings, just check that your format strings are part of that list.

如果您要检查自定义格式字符串(不是其他"或文字字符串"),则可以制作一个正则表达式来实现.

If you want to check for custom format strings (that are not "Other" or "Literal strings"), you can probably craft a regex to do it.

除此之外,由于格式字符串可以是任意个字符串,所以我认为即使都不能应用验证.

Other than that, since format strings can be arbitrary strings, I don't think validation even applies.

这篇关于简单的方法来检查FormatString是否有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆