开发者

Activator.CreateInstance with type name as string and including parameters

I am working in .Net 3.5, looking at all the various constructors for Activator.CreateInstance. I want to create an instance of a class, calling a particular constructor. I do not have the class type, only its name. I have the following, which works, but actually winds up calling the parameterless constructor first, then the one I want. This is not a terribly big deal, but the parameterless constructor calls a rather busy base constructor, and the constructor I want to call does, too.

In other words, given a type, calling CreateInstance with parameters is easy (only the last two lines below), but given only a type name, is there a better way than this?

ObjectHandle oh = Activator.CreateInstance( "MyDllName", "MyNS." + "MyClassName" );
object o = oh.Unwrap( );
object newObj = Activator.CreateInstance( o.GetType开发者_高级运维( ), new object[] { param1 } );
return ( IMyDesiredObject )newObject;

Thanks!


You can use this overload of CreateInstance. It allows you to specify the type by name (string), as well as constructor arguments (6th parameter).


The way I was able to get this to work was

  Type type = BuildManager.GetType(ServiceRef + ".SDK",false);

  Object nl = Activator.CreateInstance(type);

The BuildManager.GetType requires the fully qualified classname, in your case this is where you would pass "MyNS." + "MyClassName"

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜