方法动态调用复杂参数(C#)

时间:2016-01-14 11:51:16

标签: c# .net reflection

我想在method1中调用class1 dynamically。我不想直接使用Prm class。如何发送p parameter dynamicallyHere是一种方式,但我无法管理

namespace WindowsFormsApplicationMethodCall
{
    public class Prm
    {
        public string p1 { get; set; }
        public long p2 { get; set; }
    }
    public class Class1
    {
        public string Method1(Prm p)
        {
            return "Hello world";
        }
    }
}

用法:

private void button1_Click(object sender, EventArgs e)
{
  var ass = Assembly.LoadFrom("abc.dll");
  var business = ass.CreateInstance("WindowsFormsApplicationMethodCall.Class1");
  var mInfo = business.GetType().GetMethod("Method1");
  var anonymParameter = new { p1 = "", p2 = 2 };
  mInfo.Invoke(business,new object[]{ anonymParameter});
  //var res = mInfo.TolerantCast(new { p1 = "", p2 = 2 });
  //var param = new Dictionary<string,object>();
  //param.Add("p", result);                
}

我发现了这个错误: 类型<>f__AnonymousType0`2[System.String,System.Int32]的对象无法转换为类型

2 个答案:

答案 0 :(得分:2)

从“Prm”类创建实例并使用它

var anonymParameter = new { p1 = "", p2 = 2 };
  

var anonymParameter  = ass.CreateInstance("WindowsFormsApplicationMethodCall.Prm");
anonymParameter.GetType().GetProperty("p1").SetValue(anonymParameter,""); 
anonymParameter.GetType().GetProperty("p2").SetValue(anonymParameter,2); 

答案 1 :(得分:1)

您需要传递Prm类型的对象:

var parameter = new Prm { p1 = "", p2 = 2 };
mInfo.Invoke(business,new object[]{ parameter });