VB.NET:不可能对System.Object的实例,使用扩展方法 [英] VB.NET: impossible to use Extension method on System.Object instance

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

问题描述

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

例如:

 <扩展>
公共功能MyExtension(值作为对象)作为对象
    返回值
端功能
 

以上的功能不会为对象实例的工作:

 昏暗myObj1作为新对象()
昏暗myObj2 = myObj1.MyExtension()
 

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

更新
这个问题似乎只在VB中,在对象的成员看着向上反射(发生<一个href="http://visualbasic.about.com/od/usingvbnet/a/earlybind.htm">late-bound).

更新后ANSWERED
仅供参考,如VB有一个C#缺少的是,进口模块成员导入到全球范围,所以你仍然可以使用这个功能,而它们的包装的优点:

 暗淡myObj2 = MyExtension(myObj1)
 

解决方案

您不能直接写对象的扩展方法,但使用泛型可以达到同样的效果:

 &LT;扩展()&GT;
公共功能NullSafeToString(Of T)中(此为t)作为字符串
    如果这还不算什么。然后
       返回的String.Empty
    结束如果
    返回this.ToString()
端功能
 

请注意,您可以调用这是一切的除了的声明事物有Object类型的扩展方法。对于这些,你必须直接调用它(傻瓜证明)或通过铸造致电(这可能会失败,因为没有万向接口,所以多少有些侥幸的)。

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

Example:

<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? :)

UPDATE
The problem seems to occur only in VB, where members of object are looked-up by reflection (late-bound).

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)

解决方案

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

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 (fool proof) or call via casting (which could fail, as there is no univesal interface, so somewhat chancy).

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

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