0

我对 C# 比较陌生,并试图学习如何delegateDictionary. 我正在使用<string, Delegate配对。我的测试类如下:

namespace DelegatesHowTo
{
    class Program
    {
        protected delegate bool ModuleQuery(string parameter);

        static Dictionary<string, ModuleQuery> queryDictionary = new Dictionary<string, ModuleQuery>();

        public Program()
        {
            queryDictionary.Add("trustQuery", new ModuleQuery(queryTrustedStore));
            queryDictionary.Add("tokenQuery", new ModuleQuery(queryTokenStore));
        }

        static void Main(string[] args)
        {
            ModuleQuery MyQuery = new ModuleQuery(queryTrustedStore);
            queryDictionary.TryGetValue("trustQuery", out MyQuery);

            bool testQuery = MyQuery("TestTrusted");
            Console.WriteLine("Trusted: {0}", testQuery);
        }

        static bool queryTrustedStore(string parameter)
        {
            return parameter.Equals("TestTrusted");
        }

        static bool queryTokenStore(string parameter)
        {
            return parameter.Equals("TestToken");
        }
    }
}

然而,这条线bool testQuery = MyQuery("TestTrusted");抛出Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object. at DelegatesHowTo.Program.Main(String[] args) in c:\...

我的印象是我正在用ModuleQuery MyQuery = new ModuleQuery(queryTrustedStore);. 不过,我想这不是真的?有人可以指出我正确的方向,如何纠正这个问题?

4

1 回答 1

7

您从未运行过Program()构造函数。

因此,字典保持为空,并将TryGetValue()参数设置outnull

于 2013-08-12T20:26:27.160 回答