简体   繁体   中英

C# How to cast a generic delegate type to object and back again

I have a situation where a System.Dynamic container has to store a type in a dictionary of string to object. The type stored is a generic delegate. I need to reconstitute the type in order to call the delegate.

I know based upon the key that the object stored is a known generic delegate type. I can't figure out how to build an invoke for it. In VS debugger, looking at the object type the specialization type is known (via Reflection) and the generic delegate type is known.

UPDATE:

public delegate void MessageHandlerFunction<in T>(IMessage<T> msg, MessageReceivedInfo info);

where the T is an implementation of interface

public interface ISpecificMessage
{
    string SiteName { get; set; }
    DateTime MessageTimeStamp { get; set; }
    long MessageNumber { get; set; }
    Guid? PersonId { get; set; }
    DateTime? CreateTimeStamp { get; set; }
    DateTime? ModifyTimeStamp { get; set; }
    int? CreateTimeStampTz { get; set; }
    int? ModifyTimeStampTz { get; set; }
    int? CreateUserId { get; set; }
    int? ModifyUserId { get; set; }
    Dictionary<string, object> Payload { get; set; }
}


[Serializable]
public class SpecificMsg1 : SpecificMessage
{
}

[Serializable]
public class SpecificMsg2 : SpecificMessage
{
}

Each concrete delegate

    private void ProcessSpecificMsg1( IMessage<SpecificMsg1> msg, MessageReceivedInfo info )
    {
        _logger.InfoWrite("received message: SpecificMsg1 from siteName: {0}", msg.Body.SiteName);
    }

etc.

I have to store the delegate function in a Dictionary

Later, while running within a System.Threading.Task I need to reconstiture the delegate and call it.

var context = new Dictionary<string,object>();
context["MessageHandlerFunction"] = ProcessSpecificMsg1;
context["Msg"] = msg;
context["Info"] = info;

public class Runner
{
    public void Run( Dictionary<string,object> ctx )
    {
        var mhf = ctx["MessageHandlerFunction"];
        MessageReceiveInfo info = ctx["Info"] as MessageReceiveInfo;
        var msg = ctx["Msg"];

        //  mhf is an object type but was a delegate to a specific specialization of generic delegate.

        // How to cast to correct delegate type and call it at runtime via reflection is the question.

        ((MessageHandlerFunction<>)mhf)(msg,info);
    }
};
var message = msg as SpecificMsg1;

if (message != null)
{
   // do stuff..
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM