我有一些方法。在每种方法中重复代码。比如像这样的东西
class Sample1
{
public void SampleMethod1()
{
try
{
//Code of Method
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
}
public void SampleMethod2()
{
try
{
//Code of Method
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
public void SampleMethod3()
{
try
{
//Code of Method
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
我能做点什么不重复自己吗?最近我读了一些关于AOP的内容。也许,这是我的问题的解决方案?
答案 0 :(得分:6)
您可以创建接受Action并尝试执行它的方法:
class Sample1
{
public void SampleMethod1()
{
TryExecute(() => /* code for method */);
}
public void SampleMethod2()
{
TryExecute(() => /* code for method */);
}
private void TryExecute(Action action)
{
try
{
action();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
BTW您的示例方法满足Action委托的签名,因此您可以使用尝试执行操作的方法,并将“不安全”方法传递给它。即在类中使用Sample1
class:
private void TryExecute(Action action)
{
try
{
action();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
示例方法不应该有try-catch逻辑:
public void SampleMethod1()
{
// code for method
}
public void SampleMethod2()
{
// code for method
}
用法:
var obj = new Sample1();
TryExecute(obj.SampleMethod1);
TryExecute(obj.SampleMethod2);