开发者

Possible to create a new instance of a type without reflection?

I have a function that at the moment takes a Type variable. This function sticks it in a list and such and eventually needs will create a class of that type.

Right now I do that with

object o=MyType.GetConstructors()[0].Invoke(new object[0]);

which is pretty hacky and also will not work in medium trust due to reflection(I think). Is there a better way of doing this without reflection?

The Type is defined this way as part of a function. I need the class to be created "lazily" becau开发者_StackOverflow社区se it may not be created in the application if it's not needed. I use it for example like

AddToList(typeof(Whatever)); 

Note, I'm open to suggestions on changing the function calling. I just need the object to be created lazily and for to store the type(or however to create an object of the type) in a list.

I've considered lambdas but I'm not sure they'd work here.


Using Generics:

public void Method<T>() where T : class, new()
{
  //code
  T t = new T();
}

Using Activator (still reflection, meh):

object t = Activator.CreateInstance(yourTypeVariable);

Personally, I would prefer the first solution due to being strongly typed. However, you should be aware that both methods only allow for parameterless constructors. If you need to pass parameters, you will need reflection or expression trees.


Another alternative solution is FormatterServices.

object instance = FormatterServices.GetUninitializedObject(typeof(MyClass));

Note that the instance is created without any fields/properties initialized, even you have

class MyClass
{
   public int i = 99;
   public Object o = new object();
}

instance.i will be 0 and instance.o will be null. It's quite hard to provide a pure non-reflection solution(because always you need to call o.GetType()). This solution essentially serialize the object and then deserialize it to an object, so you don't need to use reflection to call its constructor. But there is still reflection when serialization/deserialization.


After further research on lambdas, I've discovered they will give me a much more elegant solution and it does not use reflection

So I used in my list definition

public delegate MyBaseType TypeCreator();

...
public TypeCreator Creator;

and in my function call, a simple and elegant lambda:

AddToList(()=>{return new MyType();});

I think this is quite a bit cleaner than my reflection method because it allows putting parameters into the constructor, and a few other reasons outside of the scope of this question. (It just goes with my project well)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜