[英]How to use dynamically linked dll in c#
我在我的 C# 應用程序中導入了taglib-sharp dll (已復制到我項目的 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 獲取類型時,我將能夠創建這種類型的變量。
順便問一下,這種方法是否正確?
PS 另外,我嘗試使用invoke方法,但我不確定應該將哪個對象作為第一個參數傳遞。
基於下面@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 });
}
你應該做這樣的事情:
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,那么您仍然可以獲得強類型的好處。
將其另存為對象。
object file = LibFile.Create(fi.FullName);
應該管用。
動態加載 dll 的工作方式大不相同。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.