代码之家  ›  专栏  ›  技术社区  ›  Max Yaffe

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

  •  2
  • Max Yaffe  · 技术社区  · 14 年前

    有没有任何方法可以在使用动态创建的类上使用扩展方法释放?例如:

     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)  
          {   
              ...
          }
     }
    


    有什么办法吗?
    谢谢

    4 回复  |  直到 14 年前
        1
  •  3
  •   Rune Grimstad    14 年前

    为TableType定义一个公共基类,并定义该基类上的扩展方法。这样,扩展方法也可以用于派生类。

        2
  •  4
  •   µBio    14 年前

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

        3
  •  3
  •   Lasse V. Karlsen    14 年前

    让我们看看你在问什么。

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

    很明显,要想成功,这必须是一个 Table 否则你的问题就没有意义了。

    :

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

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

        4
  •  0
  •   dkackman Srinivas Kokkula    14 年前

    在你的 somewhere Table ? 如果是这样,您可以:

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