Indexer c#中的System.StackOverflowException

Ran*_*mar 2 .net c# indexer

MyDict m = new MyDict();
m.Add("a", "a");
string s = m["a"]; // Getting exception here
Run Code Online (Sandbox Code Playgroud)

下面是Indexer的实现

public class MyDict: Dictionary<string,string>
{
    public string this[string key]
    {
        get
        {
             return this[key];
        }
        set
        {
            this[key] = value;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

例外:

An unhandled exception of type 'System.StackOverflowException' 
occurred in ConsoleApplication2.exe
Run Code Online (Sandbox Code Playgroud)

Sri*_*vel 8

您的索引器以递归方式调用自身,这就是您获得StackOverflowException异常的原因.

您可以通过以下方式修复它:

public class MyDict: Dictionary<string,string>
{
    public string this[string key]
    {
        get
        {
             return base[key];
        }
        set
        {
            base[key] = value;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,这对我来说没有意义.您可以完全删除索引器,因为基类已经为您提供了具有相同实现的索引器.

另请注意,您会收到警告'YourNameSpace.MyDict.this[string]' hides inherited member 'System.Collections.Generic.Dictionary<string,string>.this[string]'. Use the new keyword if hiding was intended..注意那些警告:)