C# 我该如何制作DoSomething???方法一种通用方法?
是否可以将C# 我该如何制作DoSomething???方法一种通用方法?,c#,generics,C#,Generics,是否可以将DoSomething方法作为单一通用方法 我的想法是: //I was thinking //DoSomethingAny(c1.Method1, "an_id"); 这是密码 using System; public class Program { static MyClass c1; public static void Main() { c1 = new MyClass(); Console.Wr
DoSomething
方法作为单一通用方法
我的想法是:
//I was thinking
//DoSomethingAny(c1.Method1, "an_id");
这是密码
using System;
public class Program
{
static MyClass c1;
public static void Main()
{
c1 = new MyClass();
Console.WriteLine("Hello World");
DoSomething1("Test1");
DoSomething2("Test2");
DoSomething3("Test3");
//I was thinking
//DoSomethingAny(c1.Method1, "an_id");
}
static int DoSomething1(string id)
{
//much more code above, but identical in all methods
var x = c1.Method1(id);
//much more code below, but identical in all methods
return x;
}
static int DoSomething2(string id)
{
var x = c1.Method2(id);
return x;
}
static int DoSomething3(string id)
{
var x = c1.Method3(id);
return x;
}
}
public class MyClass
{
public int Method1(string id)
{
Console.WriteLine("Method 1 Do Work");
return 1;
}
public int Method2(string id)
{
Console.WriteLine("Method 2 Do Work");
return 1;
}
public int Method3(string id)
{
Console.WriteLine("Method 3 Do Work");
return 1;
}
}
实际上,您可以使用委托作为参数进行重构,因此您只能编写一次
DoSomething
方法:
public static void Main()
{
c1 = new MyClass();
Console.WriteLine("Hello World");
DoSomething("Test1", c1.Method1);
DoSomething("Test2", c1.Method2);
DoSomething("Test3", c1.Method3);
}
static int DoSomething(string id, Func<string, int> action)
{
//much more code above, but identical in all methods
int x = action(id);
//much more code below, but identical in all methods
return x;
}
为什么要浪费时间和混乱的堆积如山的回答,当问题已经是如此明显的许多现有的问题?提供帮助和个性化。。。为了个性化,我的朋友。在这里,我不知道是否有一个相关的和改编的副本,为这个特定的问题。我没有搜索过,也不知道搜索什么…评论不是为了进行广泛的讨论;这段对话已经结束。
static T DoSomething<T>(string id, Func<string, T> action)
{
//much more code above, but identical in all methods
var x = action(id);
//much more code below, but identical in all methods
return x;
}