委托对象错误
本文关键字:错误 对象 | 更新日期: 2023-09-27 18:27:19
我对C#比较陌生,正在尝试学习如何从Dictionary
调用delegate
。我使用的是<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);
实例化一个对象。我想这不是真的吧?有人能为我指明正确的方向吗?如何纠正这种情况?
您从未运行过Program()
构造函数。
因此,字典保持为空,并且TryGetValue()
将out
参数设置为null
。