【问题标题】:.NET - VB - OOP - Partial Class - How to create Partial Constructors.NET - VB - OOP - 部分类 - 如何创建部分构造函数
【发布时间】:2014-08-06 04:27:07
【问题描述】:

我在文件MainFile.vb 中有一个Partial Class,其构造函数如下:

Partial Class MyAwesomeClass

    ' The constructor - Name it MainConstructor
    Public Sub New(Dim x As Integer)
        ' Some awesome code here
        Line1_of_code()
        Line2_of_code()
        Line3_of_code()
    End Sub

End Class

现在我想在同一个构造函数中添加更多代码行,即MainConstructor,但我的问题是:

  1. 我无法编辑文件MainFile.vb
  2. 我无法创建另一个构造函数
  3. 我能做的就是——因为MyAwesomeClassPartial Class;我可以创建另一个文件,例如ExtendedFile.vb 并编写我的代码行

所以我正在尝试这样做,这在.NET 中是不允许的:

Partial Class MyAwesomeClass

    ' The extended constructor - Name it ExtConstructor
    Public Sub New(Dim x As Integer) ' Boom!!!! Error: Duplicate constructor with same kind of arguments
        ' my extended awesome code here
        Line4_of_code()
        Line5_of_code()
        Line6_of_code()
    End Sub

End Class

最终我想做一些类似的事情 - 当我创建 objectMyAwesomeClass 时;它应该执行Line1_of_code()Line6_of_code()。即

Dim objAwesome As New MyAwesomeClass(5) ' Any Integer will do

应该为objAwesome 执行以下所有行(并且以相同的顺序)

Line1_of_code()
Line2_of_code()
Line3_of_code()
Line4_of_code()
Line5_of_code()
Line6_of_code()

我正在使用 .NET Fx 4.0 -- 有什么变通方法或解决方案吗?任何帮助将不胜感激。

【问题讨论】:

    标签: asp.net vb.net oop constructor partial-classes


    【解决方案1】:

    您可以将分部类视为单独文件中的代码。然后编译器会将其合并到一个类文件中。

    一种解决方案是只创建新的继承类并覆盖构造函数。

    第二种解决方案是制作共享(静态)方法构建器:

    Partial Class MyAwesomeClass
        Public Shared Function Create() As MyAwesomeClass
        ' your code goes here
        ' calling base instance creation
    

    第三种解决方案是为第二个构造函数制作不同的签名,因为你不能在类中有两个具有相同名称和签名的方法,例如

    Partial Class MyAwesomeClass
        Public Sub New(Dim x As Integer, Dim buildWithNewAwesomeImplementation as Boolean) ' 
            Me.New(x) ' calling base constructor
            If(buildWithNewAwesomeImplementation)
              Line4_of_code()
              Line5_of_code()
              Line6_of_code()
            End if
        End Sub
    End Class
    

    第一个解决方案似乎更合理。

    【讨论】:

    • 嗯,关于Partial Class,我非常了解。正如我已经说过的,我既不能编辑MainFile.vb,也不能创建另一个构造函数。所以前两个解决方案不起作用。第三种解决方案对我来说也没用,因为我的问题清楚地表明我想要“部分构造函数”之类的东西。无论如何,感谢您尝试帮助我。
    • 嗯,班级被封了吗?或者你为什么不能为这个类做一个好的包装器?另一种解决方案非常棘手,需要构造函数(AOP)的拦截器,例如使用 PostSharp codeproject.com/Articles/337564/…
    猜你喜欢
    • 2016-11-15
    • 2021-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-19
    相关资源
    最近更新 更多