如何使用类类型参数C#调用Method

时间:2019-02-27 14:53:42

标签: c# .net oop c#-4.0 reflection

我想通过反射来调用我的方法,但是我的课使用了引用类型值:

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

   }
}

如何使用以下代码传递MyEntitySave方法具有类类型参数。

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() });

1 个答案:

答案 0 :(得分:2)

首先,您需要一个Product类和一个ProductClass类:

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

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

(显然,您可以使用其他属性自定义Product类,依此类推。)

和您的ProductClass类:

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

然后您需要像这样调用您的方法:

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();
}

此代码对我来说很好...您有任何错误吗?