Dictionary with Delegates of different types: C

2019-02-18 00:53发布

问题:

There has to be a cleaner method. Currently I have:

... Constructor()
{
      parseDictionary = new Dictionary<typeOfStream, Delegate>()
            {
                {typeOfStream.SOME_ENUM_VAL, Delegate.CreateDelegate(typeof(ParseDelegate<string>), this, "MyMethod")},
                {typeOfStream.SOME_OTHER_ENUM_VAL, Delegate.CreateDelegate(typeof(ParseDelegate<XmlNode>), this, "MyOtherMethod")}
            };
}

public bool MyMethod(string some_string)
{
    ...
}

public bool MyOtherMethod(XmlNode some_node)
{
    ...
}

and I would like to get rid of "MyMethod" and MyOtherMethod and make it this.MyMethod and this.MyOtherMethod. Options?

I am open to any solution that allows me to use a Dictionary lookup, and point my data mojo into an arbitrary method (well a defined method with an arbitrary bunch of arguments) for parsing.

回答1:

Just cast to the right kind of delegate:

parseDictionary = new Dictionary<typeOfStream, Delegate>()
{
    { typeOfStream.SOME_ENUM_VAL, (ParseDelegate<string>) MyMethod) },
    { typeOfStream.SOME_OTHER_ENUM_VAL, (ParseDelegate<XmlNode>) MyOtherMethod }
};