检查 FormatString 的简单方法是否有效?

Easy way to check FormatString is valid?(检查 FormatString 的简单方法是否有效?)
本文介绍了检查 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 的简单方法是否有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)