使用基于类名的Lambda表达式创建对象

时间:2014-01-17 04:02:12

标签: vb.net reflection lambda expression

我参考下面的链接:

http://rogeralsing.com/2008/02/28/linq-expressions-creating-objects/

是否可以通过提供类名来增强它来创建对象? 基本上通过使用Lambda Expression

来实现Activator.CreateInstance可以在下面执行的操作
Dim typeName As String = "Testing.ClassNameth, Testing"
Dim typ As Type = Type.GetType(typeName)
Dim testObj = Activator.CreateInstance(typ)
Dim methodInfo As MethodInfo = testObj.GetType().GetMethod("TestPrintObject")

我这样做的目的是因为Activator.CreateInstance的性能非常慢。

谢谢!

1 个答案:

答案 0 :(得分:0)

确定。经过少量研究,下面是答案: 将以下功能添加到您的任何相关课程中:

Public Function GetActivator(Of T)(type As Type) As ObjectActivator(Of T)
    'make a NewExpression that calls the
    'ctor with the args we just created
    Dim newExp As NewExpression = Expression.[New](type)

    'create a lambda with the New
    'Expression as body
    Dim lambda As LambdaExpression = Expression.Lambda(GetType(ObjectActivator(Of T)), newExp)

    'compile it
    Dim compiled As ObjectActivator(Of T) = DirectCast(lambda.Compile(), ObjectActivator(Of T))
    Return compiled
End Function

 Public Delegate Function ObjectActivator(Of T)() As T

然后我们可以将上面的函数称为:

Dim typeName As String = "Testing.ClassNameth, Testing"
Dim typ As Type = Type.GetType(typeName)
Dim testObj As Object = YourHelperClassInstance.GetActivator(Of Object)(typ).Invoke()

希望这篇文章能帮助将来的某个人。

谢谢!