c# - instantiate a generic class using reflection -
this question has answer here:
[note: don't believe question duplicate of 1 linked above, explain in update below.]
is there way define/instantiate generic class using reflection?
so have bunch of classes, each of owns instance of generic class shares type of owner:
public class genericclass<t> { t owner { get; set; } public genericclass(t owner) { owner = owner; } } public class myclass { private genericclass<myclass> mygenericobject; public myclass() { mygenericobject = new genericclass<myclass>(this); } }
this works, of course have explicitly specify "myclass" argument in genericclass definition. i'd able this:
private genericclass<typeof(this)> mygenericobject; // error: invalid token
is there anyway dynamically specify type of generic object @ compile time, based on containing class?
update: after reading answers these questions, learned instantiate local variable so:
var mygenericobject = activator.createinstance(typeof(genericclass<>).makegenerictype(this.gettype()));
but, of course, this
keyword available inside method (so, example, put line of code in constructor of myclass
). cannot use approach define instance variable (i.e., mygenericobject
, in code above). there way specify generic instance variable dynamically?
regarding update, can pass type
makegenerictype
. example, following works:
var myobject = new myclass(); var mygenericobject = activator.createinstance(typeof(genericclass<>).makegenerictype(typeof(myclass)), myobject); console.writeline(mygenericobject.gettype());
outputs:
consoleapplication1.genericclass`1[consoleapplication1.myclass]
myobject.gettype()
same thing:
var mygenericobject = activator.createinstance(typeof(genericclass<>).makegenerictype(myobject.gettype()), myobject);
Comments
Post a Comment