<分区>
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(字符串,参数对象 [])”。用类型名称对其进行限定。
为什么?我该如何解决这个问题?