制作一个通用实例给出类型(不是实例) [英] Make a generic instance giveh the type (not instance)

查看:66
本文介绍了制作一个通用实例给出类型(不是实例)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个泛型类,用于将事件序列化到/从名称 - 值对字典中。它具有以下类签名: -



I have a generic class used to serialise an event to/from a name-value pairs dictionary. It has the following class signature:-

Public Class EventSerializer(Of TEvent As {New, IEvent})





它有一个工厂方法,可以从实例创建它因此: -



It has a factory method that can create it from an instance of the class thus:-

    Public Function Create(Of TEvent As {New, IEvent})(ByVal evt As TEvent) As EventSerializer(Of TEvent)
        Return Create(Of TEvent)()
    End Function

    Public Function Create(Of TEvent As {New, IEvent})() As EventSerializer(Of TEvent)
' creation happens here
    End Function





如何制作可创建的工厂方法序列化程序,如果传入System.Type参数: -





How would I go about making a factory method that could create the serializer if a System.Type parameter is passed in :-

Public Function Create(ByVal evtType As System.Type) As EventSerializer(Of ?)









我尝试过:



通过反射实例化类型但不是优雅也不正确..



?

What I have tried:

Instantiating the type by reflection works but is not elegant nor really correct..

推荐答案

您需要一个非通用的基类或接口,其中包含不依赖泛型类型的类成员参数。

You'd need a non-generic base class or interface containing the members of your class which don't rely on the generic type parameter.
Public MustInherit Class EventSerializer
    ' Non-generic members here...
    
    Public Shared Function Create(Of TEvent As {New, IEvent})(ByVal evt As TEvent) As EventSerializer(Of TEvent)
        Return Create(Of TEvent)()
    End Function
    
    Public Shared Function Create(Of TEvent As {New, IEvent})() As EventSerializer(Of TEvent)
        ' Magic happens here...
    End Function
    
    Public Shared Function Create(ByVal evtType As Type) As EventSerializer
        Dim method As MethodInfo = GetType(EventSerializer).GetMethod("Create", BindingFlags.Public Or BindingFlags.Static, Nothing, Type.EmptyTypes, Nothing)
        Dim result As Object = method.MakeGenericMethod(evtType).Invoke(Nothing, Nothing)
        Return DirectCast(result, EventSerializer)
    End Function
End Class

Public Class EventSerializer(Of TEvent As {New, IEvent})
    Inherits EventSerializer
    
    ' Generic members here...
End Class



您可能希望在共享字段中为通用方法缓存 MethodInfo ,以避免每次调用非泛型事实时找到它的开销ry方法。


You might want to cache the MethodInfo for the generic method in a shared field, to avoid the overhead of finding it each time you call the non-generic factory method.


这篇关于制作一个通用实例给出类型(不是实例)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆