MethodInfo calling private methods returning a null

  • Thread starter Thread starter loftty
  • Start date Start date
L

loftty

Guest
Hi All,

I am having an issue with the code below. When I run it, it returns a null when i try to invoke the printmethod2. It seems to only happen when I am trying to invoke a private method (SomeMethod2), if I try and invoke "SomeMthod", which is public, it runs fine.

Any ideas?

namespace ConsoleApp1
{
class Program
{
internal static String AssembliesPath
{
get
{
var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Script Assemblies");

if (Directory.Exists(path) == false)
{
Directory.CreateDirectory(path);
}
return path;

}
}

static void Main(string[] args)
{
var issues = CompileSourceCodeDom(code);

if (issues.Errors.Count == 0)
ExecuteFromAssembly(issues.CompiledAssembly);
}

private static string code = @"class InternalRunner
{
public void SomeMethod() { }

private void SomeMethod2() { }
}";
private static void ExecuteFromAssembly(Assembly compiledAssembly)
{
Type fooType = compiledAssembly.GetType("InternalRunner");
MethodInfo printMethod2 = fooType.GetMethod("SomeMethod2");
object foo = compiledAssembly.CreateInstance("InternalRunner");
printMethod2.Invoke(foo, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Static, null, null, CultureInfo.CurrentCulture);

}

private static CompilerResults CompileSourceCodeDom(string sourceCode)
{

CodeDomProvider cpd = new CSharpCodeProvider();
CompilerParameters cp = new CompilerParameters();
var assemblies = AppDomain.CurrentDomain
.GetAssemblies()
.Where(a => !a.IsDynamic)
.Select(a => a.Location);

cp.ReferencedAssemblies.AddRange(assemblies.ToArray());

cp.GenerateInMemory = false;
cp.GenerateExecutable = false;

String assmlocation = Path.Combine(AssembliesPath, Guid.NewGuid() + ".dll");
cp.OutputAssembly = assmlocation;

CompilerResults cr = cpd.CompileAssemblyFromSource(cp, sourceCode);

cpd.Dispose();

return cr;
}
}
}


Regards,

loftty

Continue reading...
 
Back
Top