c# - 带有 String.Format 奇怪编译器错误的扩展方法

标签 c# string extension-methods string-formatting

<分区>

Possible Duplicate:
Is it possible to create an extension method to format a string?

我有这门课:

public class Person 
{
    public string Name { get; set; }
    public uint Age { get; set; }

    public override string ToString()
    {
        return String.Format("({0}, {1})", Name, Age);
    }
}

扩展方法:

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

我想测试它,但我有以下奇怪的行为:

Person p = new Person() { Name = "Mary", Age = 24 };

// The following works
Console.WriteLine("Person: {0}".Format(p));
Console.WriteLine("Age: {0}".Format(p.Age));

// But this gives me a compiler error:
Console.WriteLine("Name: {0}".Format(p.Name));

编译错误:

无法使用对实例的引用访问成员“string.Format(字符串,参数对象 [])”。用类型名称对其进行限定。

为什么?我该如何解决这个问题?

最佳答案

因为 p.Name 是一个字符串,所以在第三种情况下你有一个不明确的调用:

string.Format(string)

对比

{string instance}.Format(object[]);

解析器选择最适合签名的方法(在您的情况下是 stringobject[])而不是扩展方法。

您可以通过重命名扩展方法或将第二个参数强制转换为对象以防止解析器选择静态方法来解决此问题:

Console.WriteLine("Name: {0}".Format((object)p.Name));

关于c# - 带有 String.Format 奇怪编译器错误的扩展方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13035591/

相关文章:

c# - 如何复制正在用 C# 编写的文件

c# - 我可以结合使用 LINQ 和 foreach 来将对象添加到集合中吗?

c# - C#从文件中读取原始字符串

ios - 扩展程序-错误(Swift3)

ruby - 扩展方法不是 "the Ruby way"吗?

c# - 是否可以在 C# 中实现 mixins?

c# - 如何在 DataGridView 上使用右键单击上下文菜单?

c# - 如何在 C# 中从 MySQL 自动递增获取 Id 并保存

c# - 我不知道为什么我在 temp 的索引 13 处得到 "0"

php 只允许使用 preg_match 的字母、数字、空格和特定符号