C# - 添加到现有(生成的)构造函数
我有一个位于生成代码中的构造函数。我不想更改生成的代码(因为重新生成时它会被覆盖),但我需要向构造函数添加一些功能。
这是一些示例代码:
// Generated file
public partial class MyGeneratedClass
{
public MyGeneratedClass()
{
Does some generated stuff
}
}
我能想到的唯一解决方案是:
// My hand made file
public partial class MyGeneratedClass
{
public MyGeneratedClass(bool useOtherConstructor):this()
{
do my added functinallity
}
}
我相当确定这会起作用,但是我的构造函数有一个蹩脚的未使用参数,我必须全部更改。有更好的办法吗?如果没有也没关系,但我想我会问。
I have a constructor that is in generated code. I don't want to change the generated code (cause it would get overwritten when I regenerate), but I need to add some functionality to the constructor.
Here is some example code:
// Generated file
public partial class MyGeneratedClass
{
public MyGeneratedClass()
{
Does some generated stuff
}
}
The only solution I can come up with is this:
// My hand made file
public partial class MyGeneratedClass
{
public MyGeneratedClass(bool useOtherConstructor):this()
{
do my added functinallity
}
}
I am fairly sure this will work, but I then have a lame unused param to my constructors and I have to go change them all. Is there a better way? If not that is fine, but I thought I would ask.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您使用的是 C# 3 并且可以更改生成器,则可以使用 部分方法:
If you're using C# 3 and can change the generator, you can use partial methods:
您的环境是否允许您从 MyGenerateClass 继承而不是将其作为分部类。然后你可以重写构造函数吗?
Would your environment allow you to inherit from MyGeneratedClass rather than have it as a partial class. You could then override the constructor?
不幸的是,假设您无法更改发电机输出,您的选择有点有限,并且考虑到您正在寻找的东西并不理想。它们是:
Assuming you can't change the generator output, unfortunately, your options are a bit limited, and not ideal considering what you're looking for. They are: