【问题标题】:calling method in static generic class without specifying type在静态泛型类中调用方法而不指定类型
【发布时间】: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&lt;T&gt;' requires 1 type arguments
  • 你知道TestClass&lt;string&gt;.Test("something");调用中可能传递的所有类型吗?
  • 为什么不能将类型参数从类中移到方法中?
  • @DavidB 有 20 种方法使用以下泛型类型,我是否应该重写 20 次以使方法调用者无需指定类型?如果我更改约束,我需要更改 20 次?

标签: c# class generics methods static


【解决方案1】:

如果您在类本身上指定泛型,则需要指定它,正如您在问题中指出的那样 - 这会起作用:

TestClass<string>.Test("something")

如果你想让编译器推断它,你需要把它放在方法上:

public static class TestClass
{
    public static void Test<T>(T something) { }
}

TestClass.Test("something");// T is infered.

现场示例:http://rextester.com/VOF10456

【讨论】:

    【解决方案2】:

    如果我理解正确,你需要这个:

    public static void Test<T>(T myValue) {. ..}
    

    然后这样称呼它:

    TestClass.Test("DoSomething");
    

    它将自动为您推断类型 string,您无需在类型参数中指定它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-09
      • 1970-01-01
      • 2015-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-28
      • 1970-01-01
      相关资源
      最近更新 更多