将扩展方法与运行时程序集一起使用
有没有办法在使用 Reelection.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 可用。
有什么办法可以解决这个问题吗?
谢谢
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使动态类实现一个接口(如果需要,可以是空接口),并向该接口添加扩展。
Make the dynamic class implement an interface (an empty one if you want), add extensions to the interface.
为您的 TableType 定义一个公共基类并在其上定义扩展方法。这样,您的扩展方法也应该可用于派生类。
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.
让我们看看你在问什么。
您询问如何让扩展方法对您的对象实例进行操作。
显然,要使其起作用,它必须是一个
Table
,否则你的问题就没有意义。因此,只需将其转换为
Table
:然后您就可以调用您的扩展方法了。
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
:and you can call your extension method just fine.
在您的
somewhere
代码中,您是否引用了Table
类型?如果是这样你可以:In your
somewhere
code do you have reference to the typeTable
? If so you can: