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

查看:22
本文介绍了检查 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天全站免登陆