简体   繁体   中英

Instantiating a class in C# from a string

I'm working on a windows phone 7 application which uses Silverlight. What I'm looking to do is create a new instance of a class given a string containing the name of the correct class I would like to create. Below is the snipit of code I'm referring to and I am trying to use it to create the new instance. I know from debugging that serviceClass contains the correct string and if I add ".cs" to it, it would now correspond directly to one of the classes I have, so why isn't it being created?

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;
    }

Any help at all or any suggestions would be greatly appreciated. Thanks for your time!

Try using the full name of the class (namespace included), without the ".cs" part. For example: YourApp.Services.YourWebViewService

如果您的字符串包含完全限定的类型名称,则可以创建实例。

Type.GetType doesn't take a string with a file name. It takes a class name or a struct name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM