System.Text.Encoding值

时间:2013-04-16 08:33:14

标签: .net vb.net visual-studio streamwriter streamwriter.write

我在使用可选参数时遇到错误,它说“需要常量表达式”

我如何解决问题?

Private Function Write_Text_To_File(ByVal Text_File As String, _
                              ByVal Text As String, _
                              ByVal Append_Text As Boolean, _
                              Optional Encoding As System.Text.Encoding = System.Text.Encoding.Default) As Boolean

    Try : Using TextFile As New IO.StreamWriter(Text_File, Append_Text, Encoding) : TextFile.WriteLine(Text) : End Using
        Return True
    Catch ex As Exception
        'Return False
        Throw New Exception(ex.Message)
    End Try

End Function
  

更新:

解决方案

#Region " Write Text to File "

' [ Write Text to File Function ]
'
' // By Elektro H@cker
'
' Examples :
'
' Write_Text_To_File("C:\Test.txt", "Text", False)
' Write_Text_To_File("C:\Test.txt", "Text", True, System.Text.Encoding.UTF8)

Private Function Write_Text_To_File(ByVal Text_File As String, _
                              ByVal Text As String, _
                              ByVal Append_Text As Boolean, _
                              Optional Encoding As System.Text.Encoding = Nothing) As Boolean
    Try
        If Encoding Is Nothing Then Encoding = System.Text.Encoding.Default
        Using TextFile As New IO.StreamWriter(Text_File, Append_Text, Encoding) : TextFile.WriteLine(Text) : End Using
        Return True
    Catch ex As Exception
        'Return False
        Throw New Exception(ex.Message)
    End Try

End Function

#End Region

1 个答案:

答案 0 :(得分:2)

  

我如何解决问题?

好吧,你只是无法使用Encoding.Default作为默认参数值。

您可以使用Nothing作为默认参数值,只需:

If Encoding Is Nothing Then
    Encoding = System.Text.Encoding.Default
End If

这意味着你不能将Nothing用于不同的含义,请注意。

另一种选择是仅使用重载 - 提供一个没有编码参数的版本,该参数仅使用编码参数调用版本,并传入Encoding.Default

另外两点需要注意:

  • 您的参数名称不符合.NET naming conventions;他们应该是camelCased
  • Encoding.Default通常是错误的默认使用(且命名不佳)。几乎.NET中的所有内容实际上都使用Encoding.UTF8作为默认编码,如果你没有指定一个;我敦促你们效仿。