我在我的C#应用程序中导入ondialogcancel
(已复制到我项目的bin / debug文件夹中),然后以下列方式使用库中的类型和方法:
using TagLib;
private void method()
{
TagLib.File file = TagLib.File.Create("C:\\temp\\some.mp3");
TagLib.Tag tag = file.GetTag(TagLib.TagTypes.Id3v2);
}
现在我想动态链接dll。在这种情况下如何实现相同的功能?
那,我试过的:
using System.Reflection
private void method()
{
Assembly TagLib = Assembly.Load("taglib-sharp");
Type TagLibFile = TagLib.GetType("File");
dynamic LibFile = Activator.CreateInstance(TagLibFile);
TagLibFile file = LibFile.Create("c:\\temp\\some.mp3");
}
在此实现中,VisualStudio表示我不能将tagLibFile变量用作类型。我想当我从dll获得一个类型时,我将能够创建这种类型的变量。
顺便问一下,这种做法是否正确?
P.S。此外,我尝试使用taglib-sharp dll方法,但我不确定我应该传递哪个对象作为第一个参数。
根据@ nawfal的awnser,我有以下工作代码:
using System.Reflection
private void method()
{
Assembly TagLib = Assembly.Load("taglib-sharp");
// get the File type
var fileType = TagLib.GetType("TagLib.File");
// get the overloaded File.Create method
var createMethod = fileType.GetMethod("Create", new[] { typeof(string) });
// get the TagTypes method that contains Id3v2 field
Type tagTypes = TagLib.GetType("TagLib.TagTypes");
// get the overloaded File.GetTag method
var getTagMethod = fileType.GetMethod("GetTag", new[] {tagTypes});
// obtain the file
dynamic file = createMethod.Invoke(null, new[] { "C:\\temp\\some.mp3" });
// obtain the Id3v2 field value
FieldInfo Id3TagField = tagTypes.GetField("Id3v2");
var Id3Tag = Id3TagField.GetValue(tagTypes);
// obtain the actual tag of the file
var tag = getTagMethod.Invoke(file, new[] { Id3Tag });
}
答案 0 :(得分:1)
你应该这样做:
private void method()
{
var assembly = Assembly.Load("taglib");
var type = assembly.GetType("namespace.File"); // namespace qualified class name
// assuming you only have one Create method, otherwise use reflection to resolve overloads
var method = type.GetMethod("Create");
dynamic file = method.Invoke(null, new[] { "C:\\temp\\some.mp3" }); // null for static methods
var tag = file.GetTag(TagLib.TagTypes.Id3v2); // not sure if you can pass those params,
// may be do reflection to get them too
}
如果你想要它是动态的,请重新思考。如果您可以引用该dll,那么您仍然可以获得强类型的好处。
答案 1 :(得分:0)
将其另存为对象。
object file = LibFile.Create(fi.FullName);
应该工作。
动态加载dll的工作方式大不相同。