通过接口动态创建类 [英] Dynamically create a class by interface

查看:81
本文介绍了通过接口动态创建类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我能够动态生成方法时,我对 .Net表达式有一定的了解。很好,很好。

I have some expirience with .Net Expressions, when I'm able to dynamically generate methods. It's fine, it's good.

但是现在我需要生成一个完整的类,并且看来唯一的方法是发出整个IL,这是完全不可接受的(

But now I need to generate a whole class, and it seems that the only way to do it is Emit whole IL which is totally inacceptable (it's impossible to support).

假设我们有以下界面:

public interface IFoo
{
    [Description("5")]
    int Bar();
    [Description("true")]
    bool Baz();
}

应转换为:

public class Foo : IFoo
{
    public int Bar() => 5;
    public bool Baz() => true;
}

如何实现?如果没有第三方工具和库,是否有可能?我知道GitHub上有很多有用的utils,但是我真的不想导入整个MVVM框架来生成一些代码。

How can I achieve it? Is it even possible without 3rd party tools and libs? I know there is plenty of useful utils on GitHub, but I really don't want to import a whole MVVM framework to just make some code generation.

使用 Expressions ,并使用我已经使用它生成的方法创建一个类。但是现在我还不知道该怎么做。

If I could just use Expressions, and create a class with methods I already generated with it. But for now I don't know how to do it.

推荐答案

我实际上正在使用 CodeGeneration.Roslyn 程序包,它使您可以集成到MSBuild管道中并生成内容。例如,请参阅我的 REST摇摇固体-> C#代码生成

I'm actually currently using CodeGeneration.Roslyn package that allows you to integrate into MSBuild pipeline and build stuff. For example, see my REST swagger or solidity -> C# codegen.

这篇关于通过接口动态创建类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆