Penguen
Penguen

Reputation: 17268

How to Invoke Method with class type parameters C#

I want to call my method via reflection, but my class uses a reference type value:

namespace XXX.Domain.XY.Products.Products.Myprovider {
public class ProductClass
{
    public void Save(Product entity)
   {

   }
}

How can I pass MyEntity by using below code? Save method has class type parameter.

Assembly loadedAssembly = Assembly.LoadFile(dll);
//if (loadedAssembly.GetName().Name== "FFSNext.Domain")

Assembly asm = Assembly.LoadFrom($"{binPath}FFSNext.Domain.dll");
Type t = asm.GetType("XXX.Domain.XY.Products.Products.Myprovider.ProductClass");
//Get and display the method.
MethodBase Mymethodbase = t.GetMethod("Save");
Console.Write("\nMymethodbase = " + Mymethodbase);

//Get the ParameterInfo array.
ParameterInfo[] Myarray = Mymethodbase.GetParameters();

Type testType = t;
object testInstance = Activator.CreateInstance(testType);

MethodInfo openMethod = testType.GetMethod("Save");

openMethod.Invoke(testInstance, new object[] { new Product() });

Upvotes: 0

Views: 1241

Answers (1)

LasymAndIris
LasymAndIris

Reputation: 110

First, you need a Product class and a ProductClass class:

public class Product
{
    public string Name { get; set; }

    public Product(string Name)
    {
        this.Name = Name;
    }
}

(You can obviously customize your Product class with other properties and so on.)

and your ProductClass class:

public class ProductClass
{
    public void Save(Product value)
    {
        // Save your product
        Console.WriteLine("Save method called successfully with the product " + value.Name);
    }
}

Then you need to invoke your method like this:

static void Main()
{
    // The namespace of your ProductClass
    string NameSpace = "SomeNameSpace.SomeSecondaryNameSpace";

    Product toSave = new Product(Name:"myProduct");

    // Load your assembly. Where it is doesn't matter
    Assembly assembly = Assembly.LoadFile("Some Assembly Path");

    // Load your type with the namespace, as you already do
    Type productClass = assembly.GetType($"{NameSpace}.ProductClass");

    // Type.GetMethod returns a MethodInfo object and not MethodBase
    MethodInfo saveMethod = productClass.GetMethod("Save");

    // Create an instance of your ProductClass class
    object instance = Activator.CreateInstance(productClass);

    // Invoke your Save method with your instance and your product to save
    saveMethod.Invoke(instance, new object[] { toSave });

    Console.ReadKey();
}

This code works fine for me... Do you have any errors with it?

Upvotes: 2

Related Questions