How can I create an instance when I only have the name of the class?
I'm looking for a solution to create singleton instances of classes, when only the names of the class will be available.
I've looked at Activator.CreateInstance()
but this needs a recast to the original object for method invoc开发者_运维技巧ation to occur. I then went in to look at how MEF
might assist, which seems to be route I want to go, but I'm not sure if this is overkill for what I'd like to achieve.
In a nutshell, I have references to web services (ASMX) with different names. These names will be exposed to a combo-box in a WinForms application when a user enters the URL to an application. From there, a couple of methods, exposed by each of the services need to be called, however, the classes will be virtual methods in the abstract class.
This sounds a lot like a plug-in framework, but the idea here is to call Microsoft specific web services in Office SharePoint Server (2007 / 2010) dynamically based on the type of foundation installed.
Hope I've given enough context.
Are you using C# 4 and .NET 4? If so, you could just use:
Type type = Type.GetType(typeName);
dynamic service = Activator.CreateInstance(type);
service.FirstCommonMethod("foo", "bar");
service.SecondCommonMethod();
Note that typeName
must at least be namespace-qualified, and if the type is in an assembly other than mscorlib
or the calling assembly, it should also be assembly-qualified.
The following code is slightly faster than using Activator.CreateInstance
, though only barely. Mostly I'm just illustrating another way to instantiate an object by Type
.
var type = Type.GetType(yourClassNamePossiblyWithLeadingNamespaces);
var expressionNew = Expression.New(type);
var typeFactory = Expression.Lambda<Func<dynamic>>(expressionNew).Compile();
var instanceOfClass = typeFactory();
EDIT: Same as Jon's answer: this needs .NET 4 and C# 4 to use dynamic
.
精彩评论