【问题标题】:Generics Warning T has same name as type from other type泛型警告 T 与其他类型的类型同名
【发布时间】:2018-07-10 08:39:31
【问题描述】:

鉴于以下

public class Service<T> : IService<T>
{
        Repository<T> _repository = new Repository<T>();
        public T Get<T>(int id)
        {
            return _repository.Get<T>(id);
        }
}
public interface IService<T>
{
        T Get<T>(int id);
}

我收到以下警告

类型参数“T”同名 作为外部类型的类型参数 'Services.IService'

我不确定这是什么问题,为什么它关心我的返回类型是否与我告诉班级的类型相同。我在这里遗漏了什么吗?

【问题讨论】:

    标签: c# generics


    【解决方案1】:

    您可以在 Get 方法的声明中省略 。您没有为 所说的 Get 方法引入新的类型参数。你返回一个 T 就足够了。

    我认为这会奏效:

    public class Service<T> : IService<T>
    {
        Repository<T> _repository = new Repository<T>();
        public T Get(int id)
        {
            return _repository.Get(id);
        }
    }
    public interface IService<T>
    {
        T Get(int id);
    }
    

    您可以在泛型和非泛型类中创建泛型方法。

    public class Foo
    {
        public T Get<T>(int a)
        {
        }
    }
    

    您也可以在泛型类中执行此操作,但使用不同的类型。

    public class Foo<T>
    {
        public S Get<S>(int a)
        {
        }
    }
    

    【讨论】:

      【解决方案2】:

      你会想要这个:

      public class Service<T> : IService<T>
      {
          Repository<T> _repository = new Repository<T>();
          public T Get(int id)
          {
              return _repository.Get<T>(id);
          }
      }
      
      public interface IService<T>
      {
          T Get(int id);
      }
      

      基本上在您尝试定义Get&lt;T&gt;() 的代码中。当您提出通用定义时,您是在说它特定于该方法,而不是整个类。

      【讨论】:

        猜你喜欢
        • 2020-04-09
        • 1970-01-01
        • 1970-01-01
        • 2022-10-14
        • 1970-01-01
        • 2017-01-21
        • 1970-01-01
        • 2021-03-27
        • 1970-01-01
        相关资源
        最近更新 更多