Indexer c#中的System.StackOverflowException

时间:2014-05-29 09:55:27

标签: c# .net indexer

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

以下是Indexer的实现

public class MyDict: Dictionary<string,string>
{
    public string this[string key]
    {
        get
        {
             return this[key];
        }
        set
        {
            this[key] = value;
        }
    }
}

例外:

An unhandled exception of type 'System.StackOverflowException' 
occurred in ConsoleApplication2.exe

2 个答案:

答案 0 :(得分:8)

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

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

public class MyDict: Dictionary<string,string>
{
    public string this[string key]
    {
        get
        {
             return base[key];
        }
        set
        {
            base[key] = value;
        }
    }
}

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

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

答案 1 :(得分:2)

m["a"]调用this[key]递归调用this[key],这就是您遇到此问题的原因。

您需要使get / set方法引用内部字典(或类似的东西)