在运行时程序集中使用扩展方法

时间:2010-09-16 21:14:10

标签: c# reflection methods

有没有办法在使用Relection.Emit动态创建的类上使用扩展方法?例如:

 class somewhere
 {
     somewhere()
     {
         // define the type here using ReflectionEmit, etc.
         Type tableType = CreateTableType(...table parameters...);

         var table = Activator.CreateInstance(tableType);
         table.Shuffle();
     } 
 }

 //... elsewhere
 public class static TableTypeExtensions   
 {
      public static Table Shuffle( this Table t)  
      {   
          ...
      }
 }

但我没有名字“Table”的类,只有Type tableType可用 有没有办法解决这个问题? 感谢

4 个答案:

答案 0 :(得分:4)

使动态类实现一个接口(如果需要,可以为空接口),为接口添加扩展。

答案 1 :(得分:3)

为TableType定义公共基类,并在其上定义扩展方法。这样,您的扩展方法也可用于派生类。

答案 2 :(得分:3)

让我们看看你在问什么。

您正在询问如何让扩展方法对您的对象实例进行操作。

显然,为了实现这一点,它必须是Table,否则你的问题毫无意义。

所以只需将其投放到Table

var table = (Table)Activator.CreateInstance(tableType);

你可以调用你的扩展方法。

答案 3 :(得分:0)

somewhere代码中,您是否引用了类型Table?如果是这样,你可以:

 Type tableType = CreateTableType(...table parameters...);

 var table = Activator.CreateInstance(tableType) as Table;
 table.Shuffle();