使用 Reflection.Emit 创建实现接口的类
我需要使用 Reflection.Emit 生成一个实现以下接口的类。
public interface IObject
{
T Get<T>(string propertyName);
}
有谁有一个例子来说明我如何将以下内容作为简单的测试用例发出?
class GeneratedObject : IObject
{
public T Get<T>(string propertyName)
{
// this is the simplest possible implementation
return default(T);
}
}
I need to generate a class using Reflection.Emit that implements the following interface.
public interface IObject
{
T Get<T>(string propertyName);
}
Does anyone have an example of how I would emit the following as a simple test case?
class GeneratedObject : IObject
{
public T Get<T>(string propertyName)
{
// this is the simplest possible implementation
return default(T);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果您使用 Reflection.Emit,您确实应该获取 Reflection 的副本.为 Reflector 发出语言插件。虽然并不完美,但它应该能让您至少 95% 地完成任何给定的发出代码。
If you're using Reflection.Emit, you really ought to grab a copy of the Reflection.Emit language add-in for Reflector. While not perfect, it should get you at least 95% of the way to any given emitted code.
我手边没有编译器,但类似这样的东西应该可以工作:
I don't have a compiler handy, but something like this should work:
我相信 AutoMapper 和/或 LinFu 将为您完成此操作。您绝对可以使用 AutoMapper 创建接口的实例,我已经做到了。
I believe AutoMapper and/or LinFu will do this for you. You can definitely create an instance of an interface using AutoMapper, I've done it.
您忘记将退货装箱:
You forgot to BOX the return:
看来,您希望通过名称快速访问对象的属性,而无需在运行时进行反射。
使用 Yappi 及其属性<>类,您可以像这样实现给定的接口:
然后像这样使用它:
您还需要 IObject 和动态类型构造吗?
It seems, you want to make fast access to object's properties by its name without reflection at run time.
Using Yappi and its Property<> class you can implement given interface like this:
and then use it like this:
Do you still need IObject and dynamic type construction?