C# 中的自定义字符串格式化程序 [英] Custom string formatter in C#

查看:22
本文介绍了C# 中的自定义字符串格式化程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C#中的字符串格式化;

String formatting in C#;

我可以使用它吗?是的.

Can I use it? Yes.

我可以实现自定义格式吗?号

Can I implement custom formatting? No.

我需要写一些东西,我可以将一组自定义格式选项传递给 string.Format,这将对特定项目产生一些影响.

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("{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

我知道我可以做诸如 .ToUpper().ToLower() 之类的事情,但我需要用字符串格式来做.

I know I can do things like .ToUpper(), .ToLower() etc. but I need to do it with string formatting.

我一直在研究 IFormatProviderIFormattable 之类的东西,但我真的不知道它们是否是我应该使用的东西,或者如何实现

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.

谁能解释一下我如何解决这个问题?

Can anyone explain how I can solve this problem?

基本原理(以防万一您想知道...)

Rationale (just in case you want to know...)

我有一个小程序,我可以在其中输入一组以逗号分隔的值和一个模板.这些项目与创建输出的模板一起传递到 string.Format 中.我想提供模板格式选项,以便用户可以控制他们希望项目的输出方式.

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. 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();
   }
}

然后像这样使用它:

 string.Format(new MyFormatter(),
            "{0:lcase}, {0:ucase}, {0:nospace}", 
            "My Test String")

这应该返回:

我的测试字符串,我的测试字符串,我的测试字符串

my test string, MY TEST STRING, MyTestString

这篇关于C# 中的自定义字符串格式化程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆