使用 CSharpCodeProvider 编译部分类
我有一个代码模板,它在项目文件夹中构建文件,并使用部分类中定义的属性来确定仍需要实现哪些属性。举个例子:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为您需要修改源代码以删除接口实现声明。
You need to modify the source to remove interface implementation declaration, I think.