Problems with Reflection

B

bikhod

Hi

Using Reflection, I am able to instantiate an instance of
my class using a constructor that takes a primitive data
type (e.g. string).

I have two other constructors, one of which takes an enum
value (Enum defined by me) and the other takes an object
whose class is defined by me. In both these cases, the
CreateInstance() function call on my assembly instance
fails with "Method not found".

Is it not possible to use Reflection with non-primitive
data types?

Below is the code I am using:

// Dummy class
public class Class2
{
public Class2() {}
}

public class Class1
{
public Class1(string s) {}
public Class1(Foo bar) {}
public Class1(Class2 class2) {}
}

// Reflection code
// object[] args = new object[] { c2 }; // *FAILS*
// object[] args = new object[] { Foo.Bar }; // *FAILS*
object[] args = new object[] { "Test input" };

Assembly assemblyInstance = Assembly.LoadFrom
("ClassLibrary1.dll");

newobj = assemblyInstance.CreateInstance(CLASS_NAME,
true,
BindingFlags.Instance|BindingFlags.InvokeMethod|BindingFlag
s.Public,
null,
args,
null,
null);

// use object
 
B

bikhod

Forgot to add Foo is an enum and c2 is an instance of
Class2:

public enum Foo
{
Bar,
Gub
}

and

Class2 c2 = new Class2();
 
M

Mattias Sjögren

In which assembly are Class2 and Foo defined? In the calling assembly,
the ClassLibrary1.dll assembly or some other?



Mattias
 
G

Guest

All three (Foo, Class1, and Class2) are defined in an
assembly different to the one that is has the reflection
code.

Basically, I have a class library assembly that has the
above three types defined in it. I am now trying to write
a Windows App assembly that uses reflection to generically
load object from the above (and other) assemblies.
 
M

Mattias Sjögren

All three (Foo, Class1, and Class2) are defined in an
assembly different to the one that is has the reflection
code.

OK, the I assume that you have a design time reference to that
assembly, otherwise code such as

object[] args = new object[] { Foo.Bar };

wouldn't even compile.

If you do have a reference to it, I don't see why you want to load it
with Assembly.LoadFrom at runtime?

To learn why this doesn't work, you should read

http://www.gotdotnet.com/team/clr/LoadFromIsolation.aspx
http://blogs.msdn.com/suzcook/



Mattias
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top