FormattableString已在C#6.0中引入.因为我们可以使用相同的字符串格式使用string对象为什么需要使用FormattableString或IFormattable.三者之间有什么区别?
我的守则
var name = "Pravin";
var s = $"Hello, {name}";
System.IFormattable s1 = $"Hello, {name}";
System.FormattableString s2 = $"Hello, {name}";
Run Code Online (Sandbox Code Playgroud)
最重要的是产生相同的结果.即'Hello Pravin'.
如果有人对此有深入的了解,我能否得到更详细的答案.
IFormattable有一个很好的参考实现吗?我打算IFormatProvider为我的对象至少有一个自定义,我想确保传递给不同的可能参数集的连线正确IFormattable.ToString(string, IFormatProvider).
到目前为止我所拥有的:
public class MyDataClass : IFormattable
{
/// <seealso cref="IFormattable.ToString(string, IFormatProvider)"/>
public string ToString(string format, IFormatProvider formatProvider)
{
ICustomFormatter formatter = (ICustomFormatter)formatProvider.GetFormat(typeof(ICustomFormatter));
return formatter.Format(format, this, formatProvider);
}
}
Run Code Online (Sandbox Code Playgroud)
但似乎应该涵盖其他潜在的情况,即:
formatProvider为null,我应该回归this.ToString()吗?formatProvider.GetFormat(typeof(ICustomFormatter))返回null,是否应该抛出一个特殊的异常?欢迎任何博客文章/代码示例/ MSDN参考.
C#中的字符串格式;
我可以用吗?是.
我可以实现自定义格式吗?没有.
我需要写一些可以传递一组自定义格式选项的内容string.Format,这会对特定项目产生一些影响.
目前我有这样的事情:
string.Format("{0}", item);
Run Code Online (Sandbox Code Playgroud)
但我希望能够用这个项目做事:
string.Format("{0:lcase}", item); // lowercases the item
string.Format("{0:ucase}", item); // uppercases the item
string.Format("{0:nospace}", item); // removes spaces
Run Code Online (Sandbox Code Playgroud)
我知道我可以做类似的事情.ToUpper(),.ToLower()但我需要用字符串格式化来做.
我一直在研究类似的事情IFormatProvider,IFormattable但我不知道它们是否应该是我应该使用的东西,或者,如何实现它们.
任何人都可以解释我如何解决这个问题?
理由(以防万一你想知道...)
我有一个小程序,我可以在其中输入逗号分隔的值集和模板.项目将string.Format与创建输出的模板一起传递.我想提供模板格式化选项,以便用户可以控制他们想要输出项目的方式.
我有一个函数,我处理了一个字符串输入.
public string Foo(string text)
{
// do stuff with text and
// return processed string
}
Run Code Online (Sandbox Code Playgroud)
我从很多地方调用了这个,我将guid转换为这样的字符串:
string returnValue = Foo(bar.ToString());
Run Code Online (Sandbox Code Playgroud)
我真正想要的是接受任何可以转换为字符串的对象类型作为输入.所以我尝试修改函数如下:
public string Foo(IFormattable text)
{
var textAsString = text.ToString();
// do stuff with textAsString
// and return processed string
}
Run Code Online (Sandbox Code Playgroud)
这意味着我的所有电话都更简单:
string returnValue = Foo(bar);
Run Code Online (Sandbox Code Playgroud)
它适用于具有.ToString方法的所有对象类型; 除了字符串:)
如果我尝试将字符串传递给函数,我会得到以下编译错误:
Argument type 'string' is not assignable to parameter type 'System.IFormattable'
Run Code Online (Sandbox Code Playgroud)
这似乎很奇怪,因为String有一个ToString()方法.
为什么这不起作用?