Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/296.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 我需要根据类型做一件特定的事情,但不确定如何实现它_C#_Generics_.net Core_Casting_C# 8.0 - Fatal编程技术网

C# 我需要根据类型做一件特定的事情,但不确定如何实现它

C# 我需要根据类型做一件特定的事情,但不确定如何实现它,c#,generics,.net-core,casting,c#-8.0,C#,Generics,.net Core,Casting,C# 8.0,我一直在构建一个消费者,其中每条消息都有一个SchemaType,它是AssemblyQualifiedName,还有一个负载,它是这种类型的对象 为了投出它,我想出了这样一个办法: Type innerType = Type.GetType(values["SchemaType"]); Type eventWithInnerType = typeof(Event<>).MakeGenericType(new[] { innerType }); var @even

我一直在构建一个消费者,其中每条消息都有一个SchemaType,它是AssemblyQualifiedName,还有一个负载,它是这种类型的对象

为了投出它,我想出了这样一个办法:

Type innerType = Type.GetType(values["SchemaType"]);
Type eventWithInnerType = typeof(Event<>).MakeGenericType(new[] { innerType });
var @event = JsonConvert.DeserializeObject(messageBody, eventWithInnerType);
Type innerType=Type.GetType(值[“SchemaType”]);
Type eventWithInnerType=typeof(Event).MakeGenericType(new[]{innerType});
var@event=JsonConvert.DeserializeObject(messageBody,eventWithInnerType);
现在,我应该根据innerType采取不同的操作。但我很困惑,不确定什么是最好的方法


例如:innerType可以是调用发送电子邮件的服务,下一条消息可以是调用服务将某些内容持久化到数据库中。

版本1:

定义一组重载
ProcessEvent()
,它接受各种
Event
,改变
T
,听起来是个好主意

ProcessEvent(Event<DbQuery> evt);
ProcessEvent(Event<ServiceCall> evt);

伟大的洞察力!事实证明,我使用工厂来实现它,以决定应该基于mesage类型创建哪个服务。
var outcome = evt.EventType switch
{
    EventType.DbCall => CallDatabase(evt),
    EventType.CallService => CallService(evt),
    // so forth
};