我想编写一个通用函数来设置音乐文件的标签字段,我正在使用“ TagLib Sharp ”库,我正在尝试编写一些可以命名为“ TagLib Sharp Helper Class ”的东西
要调用该过程,我想使用类似这样的语法来设置字段“专辑”:
TagLibSharp.Set_Tag_And_Save( _
"C:\Test.mp3", _
Function() TagLib.File.Create("").Tag.Album, _
"Test album name" _
)
问题是我不知道如何处理过程中的 Lambda 表达式......
这是所有代码(请注意解释问题所在的注释行):
#Region " TagLib Sharp "
Public Class TagLibSharp
''' <summary>
''' Stores the Taglib object.
''' </summary>
Private Shared TagFile As TagLib.File = Nothing
''' <summary>
''' Sets a Tag field and saves the file changes.
''' </summary>
Public Shared Sub Set_Tag_And_Save(ByVal File As String, _
ByVal Field As Linq.Expressions.Expression(Of Func(Of Object)), _
ByVal Value As String)
TagFile = TagLib.File.Create(File)
Dim member As Linq.Expressions.MemberExpression = _
If(TypeOf Field.Body Is Linq.Expressions.UnaryExpression, _
DirectCast(DirectCast(Field.Body, Linq.Expressions.UnaryExpression).Operand, Linq.Expressions.MemberExpression), _
DirectCast(Field.Body, Linq.Expressions.MemberExpression))
MsgBox(member.Member.Name) ' Result: "Album"
' member.Member = Value ' Here is where I don't know what to do
'
' This would be the ewuivalent:
TagFile.Tag.Album = Value
TagFile.Save()
End Sub
End Class
#End Region
更新
尝试按照 Ben Allred 解决方案的步骤解决问题,但出现异常。
TagLibSharp.Set_Tag_And_Save("c:\1.mp3", Function() TagLib.File.Create("").Tag.Album = "Test album name")
修改后的子:
Public Shared Sub Set_Tag_And_Save(ByVal File As String, _
ByVal FieldSetter As Action(Of TagLib.File))
TagFile = TagLib.File.Create(File)
FieldSetter(TagFile) ' Here throws an exception with this message: "taglib/"
' FieldSetter(TagLib.File.Create(File)) ' The same exception with this one.
TagFile.Save()
End Sub
更新 2:
现在我没有任何异常,但未设置标签字段。
TagLibSharp.Set_Tag_And_Save("c:\Test.mp3", Function(tagLibFile) tagLibFile.Tag.Title = "Test title name")
修改后的子:
Public Shared Sub Set_Tag_And_Save(ByVal File As String, _
ByVal FieldSetter As Action(Of TagLib.File))
TagFile = TagLib.File.Create(File)
MsgBox(TagFile.Tag.Title) ' Result: Unbreakeable
FieldSetter(TagFile)
MsgBox(TagFile.Tag.Title) ' Result: Unbreakeable
' TagFile.Tag.Title = "Test title name"
' MsgBox(TagFile.Tag.Title) ' Result: "Test title name"
TagFile.Save()
End Sub