簡體   English   中英

無法在字符串中使用C#中的反射/匯編/激活器實例化對象

[英]Cannot instantiate object using reflection/Assembly/Activator in c# from a string

我有一個定義類的名稱空間(我將省略代碼):

namespace My.Business.Services
{
    public class ProgressSender
    {
    }
}

該項目另存為DLL。

在我的解決方案的另一個項目中,我嘗試以各種方式將其實例化(實際上這是我的app.config中的字符串),但它們都失敗了(它確實可以在代碼中盡早創建類)。 我也包括My.Business.Services作為對該程序的引用:

namespace My.Progress.Imaging
{
  static class Program
  {
    static void Main(string[] args)
    {
        string exportItemNS = "My.Business.Services";
        string exportItemC  = "ProgressSender";
        string exportItemFull = "My.Business.Services.ProgressSender";

        //value cannot be null
        ProgressSender obj =     
         (ProgressSender)Activator.CreateInstance(Type.GetType(exportItemFull));

        //could not load type 'ProgressSender' from assembly 'My.Business.Services'
        var obj=Activator.CreateInstance(exportItemNS, exportItemC);

        //could not load type 'ProgressSender' from assembly 'My.Business.Services'
        ProgressSender s=(ProgressSender)Activator.CreateInstance(null, exportItemFull);

       //Loads ok but then classType is null
        Assembly assembly;
        assembly = Assembly.Load(exportItemNS);
        Type classType = assembly.GetType(exportItemC);

   }
 }
}

如果我從相同的命名空間甚至是系統中獲取類型,則可以:

Type t = Type.GetType("My.Progress.Imaging.Program");
t = Type.GetType("System.String");

您需要指定完整的程序集限定名稱。 僅對於mscorlib和系統類型,您可以提供類型名稱,而不提供程序集名稱。

因此,在您的情況下:

“ My.Business.Services.ProgressSender,My.Business.Services”

如果您的類型在My.Business.Services.dll程序集中。

參見https://msdn.microsoft.com/zh-cn/library/system.type.assemblyqualifiedname(v=vs.110).aspx

暫無
暫無

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

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