开发者

Using extension methods with runtime assemblies

Is there any way to use extension methods on a class that has been dynamically created using Relection.Emit? For example:

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

But I don't have the class by name "Table", only Type tableType available.

Is there any way around this?

Thanks


Make the dynamic class implement an interface (an empty one if you want), add extensions to the interface.


Define a common base class for your TableType and define the extension method on that. This way your extension method should be available for the derived classes as well.


Let's look at what you're asking.

You're asking how to get the extension method to operate on your object instance.

Obviously, for this to work, it has to be a Table, otherwise your question makes no sense.

So just cast it to Table:

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

and you can call your extension method just fine.


In your somewhere code do you have reference to the type Table? If so you can:

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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜