如何获得职业暴露相同的共享/静态方法 [英] How to get Classes to expose the same Shared/Static method

查看:131
本文介绍了如何获得职业暴露相同的共享/静态方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个派生类的基类。我想我所有的派生类中有相同的公共共享静态)方法,用自己的实现。我该怎么做呢?它甚至有可能?

I have a base class with several derived classes. I want all of my derived classes to have the same Public Shared (static) method with their own implementation. How do I do this? Is it even possible?

推荐答案

我知道这似乎是一个非常有用的功能的在设计时的,但想像这可以用于:

I know this seems like a useful feature "at design time" but imagine how this could be used:

如果 GetForms 共享静态在C# )你不必与类型的对象来区分使用哪种方法,即你不能说 BaseForm.GetForms()在某种程度上,它能够确定其中 ChildFormTypeA.GetForms() ChildFormTypeB.GetForms()实际上是所谓的。

If GetForms is Shared (static in C#) you don't have an object with a type to distinguish which method to use, i.e. you can't say BaseForm.GetForms() in some way that it can be determined which of ChildFormTypeA.GetForms() and ChildFormTypeB.GetForms() is actually called.

你能做的最好的是文件,这是打算如果你只是想显式调用 ChildFormTypeA.GetForms() ChildFormTypeB.GetForms( ),或者如果你真的需要这个概念使其成为一个工厂方法如:

The best you can do is document this is the intention if you just want explicit calls to ChildFormTypeA.GetForms() and ChildFormTypeB.GetForms(), or if you really need the concept make it a factory method e.g.

MustInherit Class BaseForm

  MustOverride Sub GetForms()

End Class

Class MyForm
   Inherits BaseForm

   Public Sub New()
   End Sub

   Overrides Sub GetForms()
   End Sub   
End Class

现在你只需要

Dim f as BaseForm = New MyForm
f.GetForms

或者 GetForms 可能是保护和从子新

编辑:这几乎是一个新的答案

保持现有code,当我刚刚需要这一点。我决定去最简单的方法是使这两个类实现的接口:

I have just needed this when maintaining existing code. I decided the simplest way to go was to make both classes implement an interface:

Interface ISharedNew
  Function SharedNew(ByVal Argument As String) As ISharedNew
End Interface

(在这种情况下,我必须通过一个通用的限制现有使用的类 T作为新,我需要构造到现在已经有一个参数,以通用的约束做不支持。)

(In this case, I have an existing use of the classes via a generic constraint T As New and I needed the constructor to now have a parameter which generic constraints do not support.)

新(简体)通用code现在是:

The new (simplified) generic code is now:

Function GetNew(Of T As {New, ISharedNew})(ByVal Argument As String) As T
  Return DirectCast((New T).SharedNew(Argument), T)
End Function

在我的情况下,新电讯对象本身被忽视了 SharedNew ,但它的类型并指定 SharedNew 相关实例,它可以创建参数一个新的 T 对象

In my case, the New T object itself is ignored by the SharedNew, but its type does specify the relevant instance of SharedNew, which creates a new T object using the Argument.

的code已被添加到从头这个答案,不必引用实际code。

这篇关于如何获得职业暴露相同的共享/静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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