Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
731 views
in Technique[技术] by (71.8m points)

c# - Easy way to check FormatString is valid?

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;
    }
}

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...