【发布时间】:2016-08-15 22:23:59
【问题描述】:
考虑下面的代码,我想做这样的事情,这不起作用但这是我想要的
class Program
{
static void Main(string[] args)
{
TestClass.Test("something");
}
}
public static class TestClass<T>
{
public static void Test(T something) { }
}
下面的代码可以工作,但我在同一个类中有 20 个通用方法,它们一遍又一遍地重复它们的约束。
public static class TestClass
{
public static void Test<T>(T something) { }
}
我不想这样做,因为我不希望使用我的代码的人指定字符串作为类型,因为“某事”已经是一个字符串
TestClass<string>.Test("something");
为了以另一种方式解释我的问题,我想从同一个类中的 20 个方法中提取相同的泛型类型和约束,我不希望它们一遍又一遍地重复,我不不希望用户在使用我的方法时指定类型,他们传入的参数将提供类型。
谢谢!
【问题讨论】:
-
你的代码工作正常,编译器会推断类型
-
@EhsanSajjad Are you sure?
Using the generic type 'Rextester.TestClass<T>' requires 1 type arguments -
你知道
TestClass<string>.Test("something");调用中可能传递的所有类型吗? -
为什么不能将类型参数从类中移到方法中?
-
@DavidB 有 20 种方法使用以下泛型类型,我是否应该重写 20 次以使方法调用者无需指定类型?如果我更改约束,我需要更改 20 次?
标签: c# class generics methods static