如何在运行时将动态转换为未知类

时间:2017-12-02 11:07:10

标签: c# dynamic runtime

我有一个动态规则引擎,我希望将类传递给它,每次都以不同的方式发送类。

例如:

Order MyOrder = new Order()
{
  OrderId = 1,
  Customer = new Customer()
  {
    FirstName = "John",
    LastName = "Doe",
    Country = new Country()
    {
      CountryCode = "AUS"
    }
  },
  Items = new List<Item>(){
    new Item(){ ItemCode = "MM23", Cost=5.25M},
    new Item(){ ItemCode = "LD45", Cost=5.25M},
    new Item(){ ItemCode = "Test", Cost=3.33M},
  }
};

我想改变这个:

var compiledRule = engine.CompileRule<Order>(rule);

到:

dynamic obj = MyOrder;
var compiledRule = engine.CompileRule<?????>(rule);

我怎样才能获得obj的类型而不是&#34; ????&#34;

1 个答案:

答案 0 :(得分:0)

我经常搜索后找到解决方案

var engine = new MRE();
var compiledRule = engine.CompileRule<Order>(rule);     

更改为:

var engine = new MRE();    
var compiledRule = typeof(MRE).GetMethod("CompileRule").MakeGenericMethod(myOrder.GetType())
                        .Invoke(engine, new object[] { rule}) as dynamic;