4
我嘗試更改方括號運算符的行爲。 現在我的問題是,如果甚至有可能做到這一點。重寫字符串的方括號運算符?
我知道我可以創建一個字符串的擴展方法有這樣的事情:
public static class StringExtension
{
public static char Substring(this string value, int position)
{
//do something
}
}
但我怎麼可以重寫括號操作? 這是行不通的:
public static class StringExtension
{
public static char this[this string value, int position]
{
//do something
}
}
怎麼可以做到。或者甚至有可能?
不,那是不可能的。您不能在靜態類中聲明索引器,並且索引器不能是靜態的。 – Shreevardhan
有一個名爲「Extension Everything」的提案 - https://github.com/dotnet/roslyn/issues/11159。但是截至目前,還不可能爲索引器編寫擴展方法。 – Evk
你想實現什麼?沒有什麼像c#中的「方括號運算符」。它是一個(保留)符號(如括號和花括號也是)。堅持你的例子和其他評論:索引一個字符串已經是可能的:'var c =「hello world」[0];'產生'char'類型的'h'。 –