使用 CSharpCodeProvider 编译部分类

发布于 2024-12-26 14:50:12 字数 646 浏览 1 评论 0原文

我有一个代码模板,它在项目文件夹中构建文件,并使用部分类中定义的属性来确定仍需要实现哪些属性。举个例子:

public partial class Thingy : IThingy
{
    public Foo Bar { get; set; }
}

public interface IThingy
{
    Foo Bar { get; set; }
    Baz Biz { get; set; }
}

模板应该生成:

public partial class Thingy
{
    Baz Biz { get; set; }
}

我可以保证模板将生成剩余的信息来满足接口的期望,因此甚至能够生成类,除了 CSharpCodeProvider 只在概念上犹豫不决在非生成的分部类中实现一半的接口。有没有办法告诉提供者忽略正在实现的接口?

编辑:我对此进行了更多思考,并想出了一种解决方法,其形式是首先将源代码实际读取到字符串中,删除接口引用,然后将代码字符串扔到 CompileAssemblyFromSource 而不是 CompileAssemblyFromFile,但这感觉非常笨拙,并且很可能会引入错误。想法?

I have a code template which builds files in a project's folder, and uses the properties defined in the partial classes to determine which properties still need to be implemented. As an example:

public partial class Thingy : IThingy
{
    public Foo Bar { get; set; }
}

public interface IThingy
{
    Foo Bar { get; set; }
    Baz Biz { get; set; }
}

and the template is supposed to generate:

public partial class Thingy
{
    Baz Biz { get; set; }
}

I can guarantee that the template will generate the remaining info to satisfy the expectations of the interface and thus would even be able to generate the class, except the CSharpCodeProvider balks at the notion of only getting half of the interface implemented in the non-generated partial class. Is there a way to tell the provider to ignore that an interface is being implemented at all?

EDIT: I've given this a little more thought, and figured a workaround in the form of actually reading the source first into a string, removing the interface references, and throwing the string of code to CompileAssemblyFromSource instead of CompileAssemblyFromFile, but that feels super kludgy and will more than likely introduce bugs. Thoughts?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

心清如水 2025-01-02 14:50:12

我认为您需要修改源代码以删除接口实现声明。

You need to modify the source to remove interface implementation declaration, I think.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文