我对 C# 比较陌生,并试图学习如何delegate
从Dictionary
. 我正在使用<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);
. 不过,我想这不是真的?有人可以指出我正确的方向,如何纠正这个问题?