当我写下面的代码时。我不能选择我的扩展方法。它不会出现。我似乎无法找到我的错误。提前谢谢。
public static class Extensions
{
public static string MySubstring(
this int index, int length)
{
StringBuilder sb = new StringBuilder();
return sb.ToString(index, length);
}
}
class SubstringExtension
{
static void Main()
{
string text = "I want to fly away.";
string result = text.
}
}
答案 0 :(得分:3)
您希望自己的扩展方法基于string
,因此您需要在扩展方法中将该字符串设为this
参数,如下所示:
void Main()
{
string text = "I want to fly away.";
string result = text.MySubstring(1, 5);
Console.WriteLine(result);
}
// Define other methods and classes here
public static class Extensions
{
public static string MySubstring(
this string str, int index, int length)
{
StringBuilder sb = new StringBuilder(str);
return sb.ToString(index, length);
}
}
结果:
想