[英]Custom string formatter in C#
String formatting in C#; C#中的字符串格式;
Can I use it? 我可以用吗? Yes.
是。
Can I implement custom formatting? 我可以实现自定义格式吗? No.
没有。
I need to write something where I can pass a set of custom formatting options to string.Format
, which will have some effect on the particular item. 我需要写一些东西,我可以将一组自定义格式选项传递给
string.Format
,这将对特定项目产生一些影响。
at the moment I have something like this: 目前我有这样的事情:
string.Format("{0}", item);
but I want to be able to do things with that item: 但我希望能够用这个项目做事:
string.Format("{0:lcase}", item); // lowercases the item
string.Format("{0:ucase}", item); // uppercases the item
string.Format("{0:nospace}", item); // removes spaces
I know I can do things like .ToUpper()
, .ToLower()
etc. but I need to do it with string formatting. 我知道我可以做像
.ToUpper()
.ToLower()
等的事情,但我需要用字符串格式化来做。
I've been looking into things like IFormatProvider
and IFormattable
but I don't really know if they are the things I should be using, or, how to implement them. 我一直在研究像
IFormatProvider
和IFormattable
这样的东西,但我真的不知道它们是我应该使用的东西,还是如何实现它们。
Can anyone explain how I can solve this problem? 任何人都可以解释我如何解决这个问题?
Rationale (just in case you want to know...) 理由 (以防万一你想知道...)
I have a small program, where I can enter a comma delimited set of values, and a template. 我有一个小程序,我可以在其中输入逗号分隔的值集和模板。 The items are passed into
string.Format
, along with the template which creates an output. 这些项目将传递给
string.Format
,以及创建输出的模板。 I want to provide template formatting options, so that the user can control how they want items to be output. 我想提供模板格式化选项,以便用户可以控制他们想要输出项目的方式。
You can make a custom formatter, something like: 您可以制作自定义格式化程序,例如:
public class MyFormatter : IFormatProvider, ICustomFormatter
{
public object GetFormat(Type formatType)
{
if (formatType == typeof(ICustomFormatter))
return this;
else
return null;
}
public string Format(string fmt, object arg, IFormatProvider formatProvider)
{
if(arg == null) return string.Empty;
if(fmt == "lcase")
return arg.ToString().ToLower();
else if(fmt == "ucase")
return arg.ToString().ToUpper();
else if(fmt == "nospace")
return arg.ToString().Replace(" ", "");
// Use this if you want to handle default formatting also
else if (arg is IFormattable)
return ((IFormattable)arg).ToString(fmt, CultureInfo.CurrentCulture);
return arg.ToString();
}
}
Then use it like: 然后使用它像:
string.Format(new MyFormatter(),
"{0:lcase}, {0:ucase}, {0:nospace}",
"My Test String")
This should return: 这应该返回:
my test string, MY TEST STRING, MyTestString
我的测试字符串,MY TEST STRING,MyTestString
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.