C# 泛型警告T与其他类型中的类型具有相同的名称
鉴于以下情况C# 泛型警告T与其他类型中的类型具有相同的名称,c#,generics,C#,Generics,鉴于以下情况 public class Service<T> : IService<T> { Repository<T> _repository = new Repository<T>(); public T Get<T>(int id) { return _repository.Get<T>(id); } } public interf
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);
}
公共类服务:iSeries
{
存储库_Repository=新存储库();
公共T获取(int id)
{
return _repository.Get(id);
}
}
公共接口设备
{
T Get(int-id);
}
我得到以下警告
类型参数“T”具有相同的名称
作为外部类型的类型参数
“服务业,服务业”
我不确定这是什么问题,为什么它关心我的返回类型是否与我告诉类的返回类型相同。我在这里遗漏了什么吗?你会想要这个:
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);
}
公共类服务:iSeries
{
存储库_Repository=新存储库();
公共T获取(int id)
{
return _repository.Get(id);
}
}
公共接口设备
{
T Get(int-id);
}
基本上,在您的代码中,您试图定义Get()
。当您使用泛型定义时,您的意思是它特定于该方法,而不是整个类。您可以在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);
}
公共类服务:iSeries
{
存储库_Repository=新存储库();
公共T获取(int id)
{
return _repository.Get(id);
}
}
公共接口设备
{
T Get(int-id);
}
可以在泛型类和非泛型类中创建泛型方法
public class Foo
{
public T Get<T>(int a)
{
}
}
公共类Foo
{
公共不获取(INTA)
{
}
}
您也可以在泛型类中执行此操作,但使用不同的类型
public class Foo<T>
{
public S Get<S>(int a)
{
}
}
公共类Foo
{
公共S Get(int a)
{
}
}