Dynamic invoke

  • Thread starter Thread starter Steve B.
  • Start date Start date
S

Steve B.

Hi

I want to instanciate an object from a string. There is a default
constructor (no parameters).
I can easily get the Type object (it is working), but when I invoke the
"new" member, I get a "NotSupportedException".

Why does it not work ?

Type t = _assembly.GetType(

"MyClass"

); // This works, the debugger show me the instance of my type object

MyClass obj = (MyClass)t.InvokeMember(

"new",

BindingFlags.CreateInstance,

null,

null,

null

); // Throw the NotSupportedException



Thanks,

Steve
 
OK I solve the problem simply using this :

MyClass obj = (MyClass)Activator.CreateInstance(t);
 
a) The InvokeMember is not suported on CF 1.0
b) Constructors are not simply members called "new".

The easiest way to create an instance of an object if you have type info and
constructor takes no parameters is to use
Activator.CreateInstance(Type)

For more complex scenarios you need to use Type.GetConstructors() to
retrieve MemberInfo array, then find the one you need and invoke it via
ConstructorInfo.Invoke. Even further, it is possible to force framework to
find an appropriate contructor for you based on the parameter types, but it
might be tricky
 
Marked as supported means "compiles'. It does not necessarily mean it works.
There are more examples like that.

As for the example on French site - it uses BindingFlags.CreateInstance
which causes the name of the method to be ignored. Again, supported only on
the desktop.
 
According your explanations, I can't see the interest of "Supported on the
CF". Not only I want to compile, but I want it to work.

How can I know if a method is ACTUALLY supported by the CF ?

Thanks,
Steve
 
Back
Top