开发者

Is there a method string.TryFormat that works similar to string.Format?

开发者 https://www.devze.com 2023-04-06 12:19 出处:网络
Is there anyway to check if a string.format argument is valid argument something like string.TryFormat .

Is there anyway to check if a string.format argument is valid argument something like string.TryFormat .

try
{
    string.Format(Format, new string[Selectors.Count]); //
}
catch (Exception)
{
    return false; 
}

I am using this method in my UI and its slow and noticable when an Exception is catched, so i was wondering if there is a better method to use开发者_如何转开发.

I could always write my own method but i wanted to know if there is a pre defined one.

An invalid string Format would be something like this string.Format("Format{0}{1}{2}",new string[]{"a","b" })


The only way a System.String.TryFormat method could work would be to catch any exceptions that might be thrown from various implementations of IFormattable.ToString (although a String.TryFormat could replace some of its own exceptions with an error-flag return, doing that while letting exceptions from TryFormat escape wouldn't be very helpful).

Worse, a TryFormat method wouldn't have any way of knowing whether any of the exceptions thrown by IFormattable.ToString might be things which shouldn't be caught. Even if the IFormattable.ToString contract required that implementations should not leak anything other than FormatException if a format specifier was invalid, one would probably want a String.TryFormat method to return false (rather than throwing) if some of the input objects were invalid but attempting to format them hadn't made anything any worse, while leaking an exception if the act of trying to format items had itself caused corruption. Unfortunately, the way the exception hierarchy is set up, there's no way a String.TryFormat could even begin to approach such semantics.

Simply put, there's not much that a String.TryFormat method could do other than use a try/catch block to stifle exceptions thrown by interior methods. There's a normal implication that TryXX methods are supposed to work better in the failure case than would be a consumer routine which just did XX in a try-catch block. If the TryFormat method is simply going to work by stifling exceptions anyway, it may as well let the consumer handle that.

0

精彩评论

暂无评论...
验证码 换一张
取 消