开发者

How can I call the constructor?

I dynamically create instances of my objects in the custom linq provider I am building using this call:

 objec开发者_如何学运维t result = Activator.CreateInstance(typeof(T));

My T type implements an abstract class that has a constructor to take an instance of another object (T is essentially a wrapper). My question is - is there a way I can explicitly call the non-default constructor so I can get rid of this:

 MyEntity entity = result as MyEntity;
 if(entity != null)
    entity.UnderlyingEntity = e; //where e is what I am wrapping 


Yes, just supply the constructor arguments after the Type object, like so:

object result = Activator.CreateInstance(typeof(T), arg1, arg2, ...);


You can use the variadic overload Activator.CreateInstance Method (Type, Object[]) and it will use the best matching constructor.


You could just call object result = Activator.CreateInstance(typeof(T), e);

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜