Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dictionary<T,Delegate> with Delegates of different types: Cleaner, non string method names?

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.

like image 663
Nick Avatar asked Dec 29 '22 04:12

Nick


1 Answers

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 }
};
like image 143
Jon Skeet Avatar answered Feb 05 '23 16:02

Jon Skeet