我对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);
实例化了一个对象。我想这不是真的吗?有人能指出我正确的方向,如何纠正这个问题?
答案 0 :(得分:7)
您从未运行过Program()
构造函数。
因此,字典保持为空,TryGetValue()
将out
参数设置为null
。