我遇到一种情况,System.Dynamic容器必须将字符串中的类型存储到对象的字典中。存储的类型是通用委托。我需要重新组合类型才能给代表打电话。
我基于密钥知道存储的对象是已知的通用委托类型。我无法弄清楚如何为它构建一个调用。在VS调试器中,查看对象类型,已知特化类型(通过Reflection),并且通用委托类型是已知的。
更新:
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);
}
等
我必须将委托函数存储在字典
中稍后,在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);
}
};
答案 0 :(得分:0)
var message = msg as SpecificMsg1;
if (message != null)
{
// do stuff..
}