Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
631 views
in Technique[技术] by (71.8m points)

.net - Disadvantages of CallbyName Function in VB.NET?

Are there any disadvantages in performance by using the CallByName function in VB.NET? Is there any better way to do the call by Name in .NET 2.0 onwards.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

CallByBame basically gives you "late binding" which is "figuring out the method at run-time" as opposed to "early binding" where the compiler figures it out for you.

With early binding you can be type safe and you'll have better performance since your code will go right to the method. The compiler will have "looked it up" for you ahead of time.

With late binding performance is slower since the method is looked up at run time and you don't have type safety - which means the method may not actually exist and you could get an exception. But this might be handy if you don't know the type of the object for some reason. I also use it to call COM object if I don't want to mess with an interop assembly.

CallByName most likely calls Type.InvokeMember. If you want to do it directly, here's some code I came up with:

Imports System.Reflection   ' For access to BindingFlags '

Friend NotInheritable Class LateBinding

    Private Const InvokePublicMethod As BindingFlags = BindingFlags.Public Or BindingFlags.Instance Or BindingFlags.InvokeMethod

    Private Const GetPublicProperty As BindingFlags = BindingFlags.Public Or BindingFlags.Instance Or BindingFlags.GetProperty

    Public Shared Function InvokeFunction(ByVal oObject As Object, ByVal sName As String, ByVal ParamArray yArguments() As Object) As Object

        Return oObject.GetType().InvokeMember(sName, InvokePublicMethod, Nothing, oObject, yArguments)

    End Function

    Public Shared Function GetProperty(ByVal oObject As Object, ByVal sName As String, ByVal ParamArray yArguments() As Object) As Object

        Return oObject.GetType().InvokeMember(sName, GetPublicProperty, Nothing, oObject, yArguments)

    End Function

End Class

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...