简体   繁体   English

将方法添加到VB.Net中的.Net类库的类?

[英]Add method to a Class of the .Net class library in VB.Net?

I would like to know whether exists a way to add a method inside a class of the .Net framework class library. 我想知道是否存在一种在.Net框架类库的类中添加方法的方法。

Let's say for example that I would like to create a Class/module that adds an IsEmpty function in the System.Windows.Forms.Clipboard Class, is this possibly?, if not, Maybe I can do it in one of the My namespace? 例如,我想创建一个在System.Windows.Forms.Clipboard类中添加IsEmpty函数的类/模块,这可能是吗?如果没有,也许我可以在My命名空间中执行此操作? ( My.Computer.clipboard ) My.Computer.clipboard

What alternatives I have instead wrapping the entire class? 我有什么替代品来包装整个班级? (and that should be done manualy? that's insane) (这应该是手工制作的吗?那是疯了)

You are looking for extension methods: http://msdn.microsoft.com/en-us/library/bb384936.aspx 您正在寻找扩展方法: http//msdn.microsoft.com/en-us/library/bb384936.aspx

An extension method can be only a Sub procedure or a Function procedure. 扩展方法只能是Sub过程或Function过程。 All extension methods must be marked with the extension attribute <Extension()> . 必须使用扩展属性<Extension()>标记所有扩展方法。 The first parameter in an extension method definition specifies which data type the method extends. 扩展方法定义中的第一个参数指定方法扩展的数据类型。

Below is a brief example. 以下是一个简短的例子。 (Fair warning, I am a C# developer, but I think this is the correct VB syntax.) (公平警告,我是C#开发人员,但我认为这是正确的VB语法。)

Imports System.Runtime.CompilerServices

Module MyExtensions

    <Extension()> 
    Public Sub MyFunction(ByVal obj As TypeToAddFunctionalityTo)
        ' functionality here
    End Sub 

End Module

Note that for the System.Windows.Forms.Clipboard class in particular, extension methods won't be of any help. 请注意,特别是对于System.Windows.Forms.Clipboard类,扩展方法将没有任何帮助。 Extension methods allow functions to be added to instance types. 扩展方法允许将函数添加到实例类型。 In the case of a class that is used statically, such as Clipboard , you won't ever have any instances of it. 对于静态使用的类(例如Clipboard ,您将不会有任何实例。

Additionally, you cannot inherit from the Clipboard class because it is defined as NotInheritable . 此外,您不能从Clipboard类继承,因为它被定义为NotInheritable Creating a wrapper class is possible, however, I would recommend simply creating a static MyClipboardUtils class that works as an addendum/sibling to the built-in class. 创建一个包装类是可能的,但是,我建议只创建一个静态MyClipboardUtils类,作为MyClipboardUtils类的附录/兄弟。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM