簡體   English   中英

C# 后期綁定和文件異常

[英]C# late binding and File exceptions

簡單的宿主應用程序通過特殊接口搜索程序集並從中導入委托列表,現在它是Func<string,string> 然后它可以執行任何Func<T,T>並且沒有問題。 當此Func任何一個嘗試訪問不存在的文件時,問題就開始了。

沒有 try-catch 塊,沒有File.Exists沒有幫助——當函數試圖訪問一個文件(無論如何,讀取、獲取流、檢查等)時——整個應用程序只是在mscorlibFileNotFound失敗。

如何解決這個問題? 應用程序真的很關鍵,我不能在應用程序中執行文件檢查,只能在程序集中。

UPD:是的,委托包含async邏輯。

UPD2:部分代碼:

    try
    {
        if(!File.Exists(filePath)) return null;

                using (StreamWriter writer = new StreamWriter(destinationFilePath))
                {
                    using (StreamReader reader = new StreamReader(filePath))
                    {
                    //some logic there
                    }
                 }
     }
    catch 
    {

    }

File.Exists() 拋出異常。

此代碼用於導入程序集。

Commands = new Dictionary<string, Func<string, string>>(); 
foreach (string f in fileNames)
                {

                    Assembly asm = Assembly.LoadFrom(f);
                    var types = asm.GetTypes();
                    foreach(Type t in types)
                    {

                        if (t.GetInterface("IMountPoint") != null)
                        {

                            var obj = Activator.CreateInstance(t);
                            var cmds = ((IMountPoint)obj).Init(EntryPoint);
                            foreach (var cmd in cmds)
                            {
                                if (!Commands.ContainsKey(cmd.Key.Trim().ToUpper()))
                                {
                                    Commands.Add(cmd.Key.Trim().ToUpper(), cmd.Value);
                                }

                            }
                        }
                    }
                }

此代碼運行委托:

string input = Console.ReadLine();
string res = Commands[command_key](input);

那是可恥的。 我正在使用后期綁定並忘記手動復制程序集,因此應用程序不會加載具有文件存在檢查的程序集,而是使用舊的程序集。 對不起大家。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM