是否有可能创建一个扩展方法格式化字符串? [英] Is it possible to create an extension method to format a string?

查看:132
本文介绍了是否有可能创建一个扩展方法格式化字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题是非常简单的。我们如何格式化C#字符串?是这样的:

the question is really simple. How do we format strings in C#? this way:

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

现在,是有可能创建一个扩展方法做这样?

Now, is it possible to create an extension method to do it this way?

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

这就是全部。

推荐答案

嗯,这是比它更复杂的样子。还有人说,这是可能的,我不怀疑他们,但它似乎并没有在单声道的情况。

Well, it's more complicated than it looks. Others say this is possible, and I don't doubt them, but it doesn't seem to be the case in Mono.

有,标准重载的格式()方法似乎优先在名称解析过程,因为一个静态方法最终被叫上一个对象实例,这是违法的编译失败。

There, the standard overloads of the Format() method seem to take precedence in the name resolution process, and compilation fails because a static method ends up being called on an object instance, which is illegal.

由于此代码:

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)与回复

The Mono compiler (mcs 2.10.2.0) replies with:

foo.cs(15,54):错误CS0176:静态
会员'的String.Format(字符串对象) '
不能用一个实例
引用来访问,具有类型名称
而不是

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

当然,上面的完全编译,如果扩展方法未命名格式(),但也许你真的想使用该名称。如果是这样的话,那么它是不可能的,或者至少不是在.NET平台的所有实现。

Of course, the above compiles cleanly if the extension method is not named Format(), but maybe you actually want to use that name. If that's the case, then it's not possible, or at least not on all implementations of the .NET platform.

这篇关于是否有可能创建一个扩展方法格式化字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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