有没有简单的方法可以自动生成这样的代码?
我有一个将在许多应用程序项目中使用的文件。这些文件的唯一区别是 Web 服务引用名称。像这样的代码:
public void Test(){
Kevin.ServiceReference1.Service1Client client = new Kevin.ServiceReference1.Service1Client();
// do something....
}
像上面的代码一样,“Kevin.ServiceReference1”将被指定的应用程序项目命名空间替换。 因此,根据 DRY(不要重复自己),我不应该只是将文件复制到许多项目并手动重命名指定的部分。有什么方法可以轻松地将模板文件的某些部分替换为与项目相关的内容吗?
i have a file which will be used across many app projects. the only difference of these files is the webservice reference name. code like this:
public void Test(){
Kevin.ServiceReference1.Service1Client client = new Kevin.ServiceReference1.Service1Client();
// do something....
}
like code above, the 'Kevin.ServiceReference1' will be replace by specified app project namespace.
so, according to DRY(don't repeat yourself), i shouldn't just copy the file to many projects and rename the specified part manually. is there any way i can easily replace some parts of my template file to something related to the project?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您研究过 Microsoft 的 T4 代码模板系统吗?这可能正是您所需要的。
链接: http://msdn.microsoft.com/en-us/vstudio/ cc308634.aspx
http://visualstudiomagazine.com /articles/2009/05/01/visual-studios-t4-code- Generation.aspx
Have you looked into Microsoft's T4 code templating system ? It might be just what you need.
Links: http://msdn.microsoft.com/en-us/vstudio/cc308634.aspx
http://visualstudiomagazine.com/articles/2009/05/01/visual-studios-t4-code-generation.aspx
这不是 DRY 的问题;而是 DRY 的问题。虽然这些文件可能看起来相似,但*您不会重复自己,因为唯一的操作(变量的声明和赋值)对于每种类型都是不同的**。
虽然您可能希望考虑为您的类提供一个共同的父级(如果它们具有共同的目的),但您的示例中没有任何内容表明这些类实际上以任何方式相关。
如果您正在寻找自动化该过程的方法,以方便自己,请查看 T4 模板(来自 Microsoft 免费),或 PostSharp。这里还有许多关于代码生成的其他线程。
This isn't a question of DRY; while the files might look similar, *you aren't repeating yourself because the one and only operation -- the declaration and assignment of a variable -- is different for every type**.
While you might want to look into giving your classes a common parent if they share a common purpose, there's nothing in your example that suggests that the classes are, in fact, related in any way.
If you're looking for ways to automate the process to make it easier on yourself, check out T4 Templates (free from Microsoft), or PostSharp. There are many other threads on here about code generation.
如果文件中唯一更改的是命名空间和类名,则可以将所有其他常见功能提取到基类中。然后,针对每种不同的用法,创建一个从基类继承的派生类。派生类可以只有一个简单的方法来返回特定的命名空间/类。
If the only thing changing in the file is the namespace and class name, you can extract all of the other common functionality into a base class. Then, for each different usage, make a derived class inheriting from the base class. The derived class could just have a simple method that would return the specific namespace/class.