模板化的代表
时间:2020-03-06 15:05:28 来源:igfitidea点击:
我有以下一段代码模式:
void M1(string s, string v) { try { // Do some work } catch(Exception ex) { // Encapsulate and rethrow exception } }
唯一的区别是方法的返回类型以及参数的数量和类型可以变化。
我想创建一个通用的/模板化的方法来处理所有代码,除了"做一些工作"部分,如何实现。
解决方案
我喜欢动作
public static void Method(Action func) { try { func(); } catch (Exception ex) { // Encapsulate and rethrow exception throw; } } public static void testCall() { string hello = "Hello World"; // Or any delgate Method(() => Console.WriteLine(hello)); // Or Method(() => AnotherTestMethod("Hello", "World")); } public static void AnotherTestMethod(string item1, string item2) { Console.WriteLine("Item1 = " + item1); Console.WriteLine("Item2 = " + item2); }