请帮帮我!我可以以某种方式自定义默认情况下在重写的方法体中显示的自动生成的代码片段吗?
默认覆盖方法看起来像
public override void Method(int A, object B)
{
base.Method(A, B);
}
我想用我自己的代码片段替换默认代码片段,例如
public override void Method(int A, object B)
{
if (A > 0)
{
// some code..
}
else
{
// some code..
}
}
修改
我有基类
public class BaseClass
{
public int Result {get;set;}
// This method depends on result
protected virtual void Method() {}
}
有很多类派生自BaseClass。所有这些都必须以相同的方式处理Method()中的Result属性。所以,我想放置一些代码,展示如何使用它。 根据我的想法,当我输入“覆盖”并在智能列表中选择“方法()”时,我得到以下代码:
public class DerivedClass: BaseClass
{
public override void Method()
{
// u have to check result property
if(result > 0)
{
// if result is positive do some logic
}
}
}
而不是默认代码段
public class DerivedClass: BaseClass
{
public override void Method()
{
base.Method();
}
}
最后
对于这种情况,使用Template Method模式是一个好主意。
感谢大家分享您的想法!
答案 0 :(得分:4)
在visual studio的Code Snippets Manager中,您可以修改MethodOverrideStub.snippet
在片段中使用参数所需的行为可能会很棘手 - 我现在正在调查这一点,但没有明显的消息。
但是,只需插入带有一些模板区域的if / else就不会太难了。
答案 1 :(得分:4)
好吧,根据代码片段让人们正确地编写你的方法并不是一个好主意。如果您希望该方法始终具有该结构,那么最好使用Template Method pattern:
public abstract class BaseClass
{
// this method forces that structure upon the subclasses
public void Foo()
{
if(result > 0)
{
DoFoo();
}
}
// this is the method that subclasses override
protected abstract void DoFoo();
}
public class DerivedClass : BaseClass
{
public override DoFoo()
{
// now you write the code here
}
}