I created a Class Library project like this
namespace ClassLibrary1
{
public class Class1
{
public string Method1(int x, string[] y)
{
if (x < 100)
{
return y[0];
}
else
{
return y[1];
}
}
}
}
then, I created a Console App project and invoked Method1
using reflection like this
using System;
using System.Reflection;
using System.Collections.Generic;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
List<object> list = new List<object>();
list.Add(5);
string[] x = new string[2] { "N", "F" };
list.Add(x);
object output = null;
string DllFile = @"C:\Users\lenovo\source\repos\ClassLibrary1\ClassLibrary1\bin\Debug\ClassLibrary1.dll";
Assembly assembly = Assembly.LoadFrom(DllFile);
var types = assembly.GetTypes();
foreach (var j in types)
{
object l = j.InvokeMember(null, BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.CreateInstance, null, null, null);
output = j.InvokeMember("Method1", BindingFlags.InvokeMethod, null, l, list.ToArray());
}
Console.WriteLine(output);
Console.ReadLine();
}
}
}
I did them successfully. Now, I'm trying to invoke Method1
that gets a struct variable as parameter using reflection. Actually, I'm trying to invoke Method1
in below code
namespace ClassLibrary1
{
public struct Person
{
public int personId;
public string firstName;
public string lastName;
}
public class Class1
{
public string Method1(int x, Person y)
{
if (x < 100)
{
return y.firstName;
}
else
{
return y.lastName;
}
}
}
}
I saw some samples and tryed them but I failed. I get an Exception every time
System.MissingMethodException: 'Method 'ClassLibrary1.Class1.Method1' not found.'
Can someone help me? what is the problem with this Exception? In my first attempt, I did not get such Exception.
Edit: below code is my attempt for invoking Method1
that gets a struct variable as parameter using reflection
using System;
using System.Reflection;
using System.Collections.Generic;
namespace ConsoleApp1
{
public struct Person
{
public int personId;
public string firstName;
public string lastName;
}
class Program
{
static void Main(string[] args)
{
List<object> list = new List<object>();
list.Add(5);
Person x = new Person();
x.personId = 1;
x.firstName = "N";
x.lastName = "F";
list.Add(x);
object output = null;
string DllFile = @"C:\Users\lenovo\source\repos\ClassLibrary1\ClassLibrary1\bin\Debug\ClassLibrary1.dll";
Assembly assembly = Assembly.LoadFrom(DllFile);
var types = assembly.GetTypes();
foreach (var j in types)
{
object l = j.InvokeMember(null, BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.CreateInstance, null, null, null);
output = j.InvokeMember("Method1", BindingFlags.InvokeMethod, null, l, list.ToArray());
}
Console.WriteLine(output);
Console.ReadLine();
}
}
}
Aucun commentaire:
Enregistrer un commentaire