c# - 是否可以创建扩展方法来格式化字符串?

这个问题真的很简单。我们如何在 C# 中格式化字符串?这样:

 string.Format("string goes here with placeholders like {0} {1}", firstName, lastName);

现在,是否可以创建一个扩展方法来做到这一点?

 "string goes here {0} {1}".Format(firstName, lastName);

就是这样。

最佳答案

嗯,它比看起来更复杂。其他人说这是可能的,我不怀疑他们,但在 Mono 中似乎并非如此。

在那里,Format() 方法的标准重载似乎在名称解析过程中具有优先权,并且编译失败,因为最终在对象实例上调用了静态方法,这是非法的.

鉴于此代码:

public static class Extensions
{
    public static string Format(this string str, params object[] args)
    {
        return String.Format(str, args);
    }
}

class Program
{
    public static void Main()
    {
        Console.WriteLine("string goes here {0} {1}".Format("foo", "bar"));
    }
}

Mono 编译器 (mcs 2.10.2.0) 回复:

foo.cs(15,54): error CS0176: Static member `string.Format(string, object)' cannot be accessed with an instance reference, qualify it with a type name instead

当然,如果扩展方法没有命名为Format(),上面的代码编译干净,但也许你真的想使用那个名字。如果是这种情况,那么这是不可能的,或者至少不是在 .NET 平台的所有实现上。

https://stackoverflow.com/questions/6587243/

相关文章:

excel - 我可以仅使用 excel 的图表格式在月桶中显示每日数据吗?

c# - 我应该使用什么页面图像生成技术?

excel - 即使第一个数字是 0 vba,也将数字格式化为两位数

html - HTML anchor 标记中超链接文本的内联换行

iphone - 具有默认时区的 NSDateFormatter 给出的日期与 NSDate 描述方

c++ - 我可以给出一个流来在 C++ 中的数字上打印前导零的指令是什么?

wpf - 如何格式化标签以具有显示格式字符串?

php - Aptana PHP Formatter - 使用自定义格式规则

excel - 创建数据透视表时日期值的排序问题

php - 格式化关联数组声明