c#如何将泛型委托类型强制转换为对象类型



我有一个系统。动态容器必须将类型存储在字符串到对象的字典中。存储的类型是泛型委托。为了调用委托,我需要重新构造类型。

根据键,我知道存储的对象是已知的泛型委托类型。我不知道如何为它构建调用。在VS调试器中,查看对象类型,特殊化类型是已知的(通过反射),泛型委托类型是已知的。

更新:

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

其中T是接口

的实现
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
{
}

每个具体委托

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

等。

我必须将委托函数存储在Dictionary中

之后,当在System.Threading.Task中运行时,我需要重新构造委派并调用它。

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..
}

相关内容

  • 没有找到相关文章

最新更新