VB.NET:无法在 System.Object 实例上使用扩展方法 [英] VB.NET: impossible to use Extension method on System.Object instance

查看:29
本文介绍了VB.NET:无法在 System.Object 实例上使用扩展方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以为 System.Object 的所有子类(一切)创建一个扩展方法吗?

Can I make an Extension method for all the subclasses of System.Object (everything)?

示例:

<Extension>
Public Function MyExtension(value As Object) As Object
    Return value
End Function

以上函数不适用于对象实例:

The above functions won't work for object instance:

Dim myObj1 As New Object()
Dim myObj2 = myObj1.MyExtension()

编译器不接受,是我电脑的问题吗?:)

The compiler does not accept it, is the problem in my computer? :)

更新
这个问题似乎只发生在 VB 中,其中对象的成员是通过反射查找的 (后期绑定).

回答后更新
仅供参考,因为 vb 具有 C# 缺乏的优势,即导入模块的成员被导入到全局范围,因此您仍然可以在没有包装器的情况下使用这些函数:

UPDATE AFTER ANSWERED
FYI, as vb has an advantage that C# lacks that is, members of imported Modules are imported to the global scope so you can still use this functions without their wrapper:

Dim myObj2 = MyExtension(myObj1)

推荐答案

您不能直接为 Object 编写扩展方法,但使用泛型可以达到相同的效果:

You can not directly write an extension method for Object, but using generics you can achieve the same result:

<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 类型的所有内容.对于那些,您必须直接调用它(完整证明)或通过强制转换调用(这可能会失败,因为没有通用接口,所以有点偶然).

Note that you can call this as an extension method on everything except things that are declared to have the type Object. For those, you have to either call it directly (full proof) or call via casting (which could fail, as there is no univesal interface, so somewhat chancy).

这篇关于VB.NET:无法在 System.Object 实例上使用扩展方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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