gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 17:09:20 25 4
gpt4 key购买 nike

<分区>

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(字符串,参数对象 [])”。用类型名称对其进行限定。

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com