是否可以编写一个通用的c#方法,如下所示:
MyClass.Function1<string>()
MyClass.Function1<IEnumerable<string>>()
MyClass.Function1<IDictionary<string, string>>()
MyClass.Function1<IDictionary<string, IEnumerable<string>>>()
T可以是任何东西
T = string
T = IEnumerable<string>
T = IDictionary<string, string>
T = IDictionary<string, IEnumerable<string>>
第二个问题
我可以创建一个静态方法,取决于类型吗?
string GetSth().Function1();
IEnumerable<string> GetSth().Function1()
IDictionary<string, string> GetSth().Function1()
IDictionary<string, IEnumerable<string>> GetSth().Function1()
答案 0 :(得分:1)
对于第一个问题,定义一个泛型类,其中包含共享接口的位置,例如IEnumerable或没有任何where子句:
public class MyClass
{
public static string Function1<T>()
{
return typeof(T).FullName;
}
public static string Function2<T>() where T : IEnumerable
{
return typeof(T).FullName;
}
}
第二个定义Extension Methods:
public static class MyClass_Extensions
{
public static string StaticMethod1(this object obj)
{
return obj?.ToString();
}
public static string StaticMethod2(this IEnumerable obj)
{
return obj?.ToString();
}
}
所以我们可以编写这个测试方法:
class Program
{
static void Main(string[] args)
{
Console.WriteLine(MyClass.Function1<string>());
Console.WriteLine(MyClass.Function1<IEnumerable<string>>());
Console.WriteLine(MyClass.Function1<IDictionary<string, string>>());
Console.WriteLine(MyClass.Function1<IDictionary<string, IEnumerable<string>>>());
Console.WriteLine(MyClass.Function2<string>());
Console.WriteLine(MyClass.Function2<IEnumerable<string>>());
Console.WriteLine(MyClass.Function2<IDictionary<string, string>>());
Console.WriteLine(MyClass.Function2<IDictionary<string, IEnumerable<string>>>());
// Static Method:
var strObj = "string";
Console.WriteLine(strObj.StaticMethod1());
Console.WriteLine(strObj.StaticMethod2());
IEnumerable<string> listObj = new List<string>();
Console.WriteLine(listObj.StaticMethod1());
Console.WriteLine(listObj.StaticMethod2());
IDictionary<string, string> dicObj = new Dictionary<string, string>();
Console.WriteLine(dicObj.StaticMethod1());
Console.WriteLine(dicObj.StaticMethod2());
IDictionary<string, IEnumerable<string>> dicLisObj = new Dictionary<string, IEnumerable<string>>();
Console.WriteLine(dicLisObj.StaticMethod1());
Console.WriteLine(dicLisObj.StaticMethod2());
}
}