【问题标题】:Inheriting StreamWriter with new filename使用新文件名继承 StreamWriter
【发布时间】:2016-07-21 08:31:03
【问题描述】:

我想编写如下所示的代码:

Public Class LogFile
    Inherits StreamWriter

    Private LogsDirectory As String = Application.StartupPath & "\" & "logs\"

    Public Sub New(shortName As String)            
        Dim fullFilePath As String = LogsDirectory & shortName & "_" & Format(Now, "HHmmss") & ".log"    
        MyBase.New(fullFilePath)
    End Sub

End Class

但是我不得不这样做(因为Sub New 的第一条语句必须是基础构造函数):

 Public Class LogFile  
     Inherits StreamWriter       

    Public Sub New(shortName As String)              
        MyBase.New(Application.StartupPath & "\" & "logs\" & shortName & "_" & Format(Now, "HHmmss") & ".log")
    End Sub

End Class

有没有办法“解决”这个问题?在这种情况下没关系,但可以想象我想做更多的处理,而不是一行。

【问题讨论】:

  • LogsDirectory 变量必须先赋值,然后才能使用。看起来它在代码中是自动的,但这只是语法糖,构造函数负责处理。但是等等,你正在编写构造函数。鸡蛋必须先于鸡。这同样适用于 MyBase.New()。

标签: .net vb.net inheritance streamwriter


【解决方案1】:

只要是 SharedLogsDirectory 也必须是 Shared),您就可以使用函数实现您想要的目标

以下编译:

Public Class LogFile
    Inherits StreamWriter

    Public Sub New(shortName As String)
        MyBase.New(InitFunction(shortName))
    End Sub

    Private Shared LogsDirectory As String = Application.StartupPath & "\" & "logs\"

    Private Shared Function InitFunction(shortname As String) As String
        Dim fullFilePath = LogsDirectory & shortname & "_" & Format(Now, "HHmmss") & ".log"
        Return fullFilePath
    End Function
End Class

【讨论】:

  • 抱歉,在简化我的代码以仅包含相关元素时,我错过了其中的一个关键元素 - 我已经编辑了我的问题。
猜你喜欢
  • 2011-01-17
  • 2014-09-21
  • 2019-02-15
  • 2011-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多