【问题标题】:difference T Get<T>(int id) and T Get(int id)T Get<T>(int id) 和 T Get(int id) 的区别
【发布时间】:2012-06-25 11:28:00
【问题描述】:

谁能告诉我两者的区别

public T Get<T>(int id)

public T Get(int id)

【问题讨论】:

  • 表示在运行时定义的泛型类型参数。这种类型要么在类实例化期间指定(您的第二行需要在对象创建期间定义 T),要么在调用方法时(您的第一行代码)。
  • @davenewza:您的评论在两种情况下都是正确的,实际上对于 ant 泛型是通用的。诸如“T 在这里是什么意思?”之类的东西。或“什么是泛型?” ;)

标签: c# .net entity-framework generics


【解决方案1】:

比较:

class First
{
    public T Get<T>(int id) // T is declared in the method scope
    {
    }
}

class Second<T>
{
    public T Get(int id) // T is declared in the class scope
    {
    }
}

还有第三种情况:

class Third<U>
{
    public T Get<T>(int id) // T is declared in the method scope when class scope has another generic argument declared
    {
    }
}

【讨论】:

【解决方案2】:

不同之处在于,如果之前没有定义 T,则使用第一种类型的声明。即。

public class MyClass
{
    public T Get<T>(int id);
}

当 T 已经在类级别定义时,第二个。即。

public class MyClass<T>
{
    public T Get(int id);
}

在这种情况下,您还可以使用第一种类型的声明 - 这实际上是简写。效果没有区别。

编辑 事实上,第二个声明只要求 T 在范围内,另一个例子是嵌套类...

public class MyClass<T>
{
  public class NestedClass
  {
    public T Get(int i);
  }
}

【讨论】:

    【解决方案3】:

    阅读Generics,然后才能在代码中使用它们。

    【讨论】:

      猜你喜欢
      • 2016-09-07
      • 2014-09-15
      • 1970-01-01
      • 2017-08-21
      • 2019-11-08
      • 2011-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多