2012-02-14 39 views
0

我有以下代码:重构与通用和代表

Type1 Method1(Type2 p) 
{ 
    try 
    { 
     return DoSomething(p) 
    } 
    catch{ExceptionType1} 
    { 
    } 
    catch{ExceptionType2} 
    { 
    } 
    catch{ExceptionType3} 
    { 
    } 
} 

Type3 Method2(Type4 p) 
{ 
    try 
    { 
     return DoSomethingElse(p) 
    } 
    catch{ExceptionType1} 
    { 
    } 
    catch{ExceptionType2} 
    { 
    } 
    catch{ExceptionType3} 
    { 
    } 
} 

我如何重构这段代码有类似:

TResult ExceptionalMethod(Methodx(T)){ 
    try 
    { 
     return Methodx(T); 
    } 
    catch{ExceptionType1} 
    { 
    } 
    catch{ExceptionType2} 
    { 
    } 
    catch{ExceptionType3} 
    { 
    } 
} 

谢谢 Adrya

回答

1

这工作:

TResult ExceptionalMethod<T, TResult>(Func<T, TResult> methodx, T parameter){ 
    try 
    { 
     return methodx(parameter); 
    } 
    catch(ExceptionType1) 
    { 
    } 
    catch(ExceptionType2) 
    { 
    } 
    catch(ExceptionType3) 
    { 
    } 

    return default(TResult); 
} 

我希望你在这些渔获物中做一些有用的事情。

编辑
如果你没有在你的框架版本的Func<T, TResult>委托,您可以轻松地添加它,没有什么特别的吧:

public delegate TResult Func<T, TResult>(T arg); 
+0

您需要输入功能,适用于为好,而东西返回,如果有例外。 – 2012-02-14 13:45:33

+0

您使用T作为参数 – 2012-02-14 13:52:36

+0

谢谢,是的,我对异常做了些什么。你能否将代码改为3.0版本的.net框架。 Func仅在3.5版本中推出。 – Adrya 2012-02-15 09:36:17

0

听起来像是你只是想:

TResult ExceptionalMethod<TSource, TResult>(Func<TSource, TResult> func, 
              TSource input) 
{ 
    try 
    { 
     return func(input); 
    } 
    catch(ExceptionType1) {} 
    catch(ExceptionType2) {} 
    catch(ExceptionType3) {} 
    return default(TResult); 
} 

但是,您还应该重新考虑捕获异常并像这样吞下它们 - 您的真实代码是否对它们做了一些有用的事情,例如日志记录?

请注意最后的返回语句 - 这可能不合适,但如果您要捕获这些例外情况,则必须返回

0
TResult ExceptionalMethod<TResult>(Action<T> action)){ 
{ 
    ... 
} 
0

这是一个完整的样本做你想要使用的是什么代表和FUNC:

using System; 

namespace GenericsDelegates 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      string test1 = ExceptionalMethod(TestMethod1, "test"); 
      string test2 = ExceptionalMethod(TestMethod2, "test"); 

      Console.WriteLine(test1); 
      Console.WriteLine(test2); 
     } 

     public static TResult ExceptionalMethod<T, TResult>(Func<T, TResult> func, T param) 
     { 
      return func(param); 
     } 

     public static string TestMethod1(string param) 
     { 
      return "TestMethod1-" + param; 
     } 

     public static string TestMethod2(string param) 
     { 
      return "TestMethod2-" + param; 
     } 
    } 
}