以下代码无法在C#中使用错误Cannot implicitly convert type 'string' to 'String'
进行编译。无法将类型'字符串'隐式转换为'字符串'
void Main()
{
Console.Write("Hello".Append("Mark"));
}
public static class Ext
{
public static String Append<String>(this String str, String app)
{
return str + " " + app;
}
}
您可以通过扩展方法去除类型参数修正编译错误,但我不知道为什么这个不能编译因为typeof(string) == typeof(String)
评估为true
。
下也工作得很好:
void Main()
{
Console.Write("Hello".Append("Mark"));
}
public static class Ext
{
public static string Append<String>(this String str, string app)
{
return str + " " + app;
}
}
你为什么有这里有一个类型约束''? –
2015-02-09 11:53:43
我正在写一些使用T参数的扩展方法,但是这只对String有意义,所以我用String替换了T,并且很惊讶地收到错误。它当然不需要在那里。以下代码编译并运行得很好: 'void Main() { Console.Write(“Hello”.Append(“Mark”)); } 公共静态类分机 { 公共静态字符串追加(此字符串str,字符串app) { 返回STR + “” +应用; } }' –
MarkFl
2015-02-09 11:57:03
由于第一个参数'this String str'已经定义了目标类型,所以不需要扩展方法。 – helb 2015-02-09 11:57:55