GetConstructor does not work when the constructor has ref paramete

G

Guest

here is the simplified code: the myCor is set to null when run the program.
but if remove the "ref" from the constructor's parameter, myCor gets a valid
value.

Please help!!! thanks.


Type myType = myAssembly.GetType("MyClass")
Type[] parameters = new Type[1];
parameters[0] = typeof(object);
ConstructorInfo myCor = myType .GetConstructor(parameters);

public class MyClass
{
public MyClass(ref object obj)
{
object o = obj;
}
}
 
M

Markus

here is the simplified code: the myCor is set to null when run the
program. but if remove the "ref" from the constructor's parameter,
myCor gets a valid value.

This is not a solution right now, but to be honest, I never have
required the ref-keyword in a constructor... I believe there is a better
way to handle this, seems to me as a week design (maybe I am wrong,
because I don't see the whole context).

Markus
 
J

Jon Skeet [C# MVP]

here is the simplified code: the myCor is set to null when run the program.
but if remove the "ref" from the constructor's parameter, myCor gets a valid
value.

As Markus said, it's very rare to need "ref" in a constructor (and I'd
need to see a good example to persuade me that it's a good idea) but
you can make GetConstructor work. Here's a short but complete example:

using System;
using System.Reflection;

public class MyClass
{
public MyClass(ref object obj)
{
Console.WriteLine ("Called");
}
}

class Test
{
static void Main()
{
Type type = typeof(MyClass);
Type[] parameterTypes = new Type[]
{ typeof(object).MakeByRefType() };
ConstructorInfo constructor = type.GetConstructor
(parameterTypes);

object[] args = new object[1];
constructor.Invoke(args);
}
}
 

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