簡體   English   中英

從字符串實例化C#中的類

[英]Instantiating a class in C# from a string

我正在使用Silverlight的Windows Phone 7應用程序上工作。 我想做的是給一個包含要創建的正確類名的字符串創建一個類的新實例。 下面是我所引用的代碼片段,我試圖用它來創建新實例。 通過調試,我知道serviceClass包含正確的字符串,如果我向其中添加“ .cs”,它現在將直接對應於我擁有的一個類,那么為什么不創建它呢?

WebViewService foundService; //From above
....
....
services.TryGetValue(mode, out foundService); //Find service
if (foundService == null)
   {
            string serviceClass;
            serviceRegistry.TryGetValue(mode, out serviceClass); //Find serviceClass
            if (serviceClass != null) //create new web service if one is found
            {
                try
                {
                    //TODO: This is not working properly, should create an instance of some child class of WebViewService
                     foundService = (WebViewService)System.Activator.CreateInstance(Type.GetType(serviceClass+".cs"));
                     services.Add(mode, foundService);
                }
                catch
                {
                    //But instead it always ends up here with ArgumentNullExeption
                }
            }
        }
        return foundService;
    }

任何幫助或任何建議將不勝感激。 謝謝你的時間!

嘗試使用類的全名(包括名稱空間),不要使用“ .cs”部分。 例如: YourApp.Services.YourWebViewService

如果您的字符串包含完全限定的類型名稱,則可以創建實例。

Type.GetType不使用帶有文件名的字符串。 它采用類名或結構名。

暫無
暫無

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

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