Shi*_*mmy 37 .net vb.net extension-methods object late-binding
我可以为System.Object(所有)的所有子类创建一个Extension方法吗?
例:
<Extension>
Public Function MyExtension(value As Object) As Object
    Return value
End Function
以上函数不适用于对象实例:
Dim myObj1 As New Object()
Dim myObj2 = myObj1.MyExtension()
编译器不接受它,是我电脑中的问题?:)
更新
 
问题似乎只发生在VB中,其中对象的成员通过反射(后期绑定)查找.
在回答
 
FYI 之后更新,因为vb具有C#缺少的优点,导入模块的成员被导入到全局范围,因此您仍然可以在没有包装器的情况下使用此函数:
Dim myObj2 = MyExtension(myObj1)
Dan*_*Tao 13
看到我前段时间问过这个问题.基本上,如果你愿意,可以 在VB.NET中扩展 Object ; 但为了向下兼容的原因,没有变量声明为Object将能够使用您的扩展方法.这是因为VB.NET支持后期绑定Object,因此尝试访问扩展方法将被忽略,有利于尝试从相关对象的类型中查找同名方法.
所以采用这种扩展方法,例如:
<Extension()>
Public Sub Dump(ByVal obj As Object)
    Console.WriteLine(obj)
End Sub
这个扩展方法可以在这里使用:
' Note: here we are calling the Dump extension method on a variable '
' typed as String, which works because String (like all classes) '
' inherits from Object. '
Dim str As String = "Hello!"
str.Dump()
但不是这里:
' Here we attempt to call Dump on a variable typed as Object; but '
' this will not work since late binding is a feature that came before '
' extension methods. '
Dim obj As New Object
obj.Dump()
问问自己为什么扩展方法不适dynamic用于C#中的变量,你会发现解释是一样的.
jmo*_*eno 10
您不能直接为Object编写扩展方法,但使用泛型可以获得相同的结果:
<Extension()>
Public Function NullSafeToString(Of T)(this As T) As String
    If this is Nothing Then
       Return String.Empty
    End If
    Return this.ToString()
End Function
请注意,除了声明具有Object类型的内容之外,您可以将其作为扩展方法调用.对于那些,你必须直接调用它(傻瓜证明)或通过强制调用(可能失败,因为没有univesal接口,所以有点chancy).