如何验证.NET格式字符串

本文关键字:NET 格式 字符串 验证 何验证 | 更新日期: 2023-09-27 17:57:44

我开发了一个C#解决方案,要求用户可以自定义显示的实数的格式,包括标题、数字和单位。

我允许用户指定一个与string.Format()的第一个参数完全匹配的格式字符串,这样他就可以按照自己想要的方式调整显示。

例如,{0}: {1:0.00} [{2}]将显示Flow rate: 123.32 [Nm³/h]

用户知道如何使用此格式设置功能,{0}是标题,{1}是数字,{2}是位数,并且对.NET格式设置有最低限度的了解。

然而,在某个时候,我必须验证他输入的格式字符串,我没有找到其他方法,只能将其用于伪值,并以这种方式捕获FormatException

try
{
    string.Format(userFormat, "", 0d, "");
    // entry acceptance...
}
catch(FormatException)
{
    messageBox.Show("The formatting string is wrong");
    // entry rejection...
}

当发生错误时,这不是最方便用户的。。。

NET格式字符串是否可以用更优雅的方式进行验证?有没有办法在出现故障时向用户提供一些提示?

如何验证.NET格式字符串

很可能有更好的和更有效的方法来实现这一点。这只是一种可能的方式

但这就是我的想法。

public bool IsInputStringValid(string input)
    {
        //If there are no Braces then The String is vaild just useless
        if(!input.Any(x => x == '{' || x == '}')){return true;}
        //Check If There are the Same Number of Open Braces as Close Braces
        if(!(input.Count(x => x == '{') == input.Count(x => x == '}'))){return false;}
        //Check If Value Between Braces is Numeric
        var tempString = input; 
        while (tempString.Any(x => x == '{'))
        {
            tempString = tempString.Substring(tempString.IndexOf('{') + 1);
            string strnum = tempString.Substring(0, tempString.IndexOf('}'));
            int num = -1;
            if(!Int32.TryParse(strnum, out num))
            {
                    return false;
            }       
        }
        //Passes Validation
        return true;
    }

Fiddle在这里:http://dotnetfiddle.net/3wxU7R

您尝试过吗:

catch(FormatException fe)
{
     messageBox.Show("The formatting string is wrong: " + fe.Message);
// entry rejection...
}