저는 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");
은 내가 ModuleQuery MyQuery = new ModuleQuery(queryTrustedStore);
와 객체를 인스턴스화 된 인상을 Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object. at DelegatesHowTo.Program.Main(String[] args) in c:\...
이었다가 발생
다음과 같이 내 테스트 클래스이다. 이게 사실이 아니란 것 같아요? 누군가가 어떻게 올바른 방향으로 나를 가리킬 수 있을까요?
테스트 프로그램이 잘못되었으므로 프로그램 클래스 생성자는 인스턴스를 생성하지 않으므로 실행되지 않습니다. Main() 안에 Dictionary <>. Add() 문을 이동하거나 정적 생성자를 사용하십시오. –