使用 Visual Studio 2010 的发布版本,我认为与 VS2008 的“实现接口(interface)”扩展存在差异
如果我指定一个接口(interface)并在类中实现它:
public interface IRepository<T> where T : IModel
{
T Get<T>(int id);
void Update<T>(T item);
int Add<T>(T item);
}
public class MockRepository : IRepository<MockUser>
{
// ...
}
然后使用“实现接口(interface)”扩展并得到这个:
public class MockRepository : IRepository<MockUser>
{
public T Get<T>(int id)
{
throw new NotImplementedException();
}
public void Update<T>(T item)
{
throw new NotImplementedException();
}
public int Add<T>(T item)
{
throw new NotImplementedException();
}
}
而不是我所期望的
public class MockRepository : IRepository<MockUser>
{
public MockUser Get<MockUser>(int id)
{
throw new NotImplementedException();
}
public void Update<MockUser>(MockUser item)
{
throw new NotImplementedException();
}
public int Add<MockUser>(MockUser item)
{
throw new NotImplementedException();
}
}
IDE 使用通用接口(interface)定义 T
中的类型变量名称,而不是指定的具体类型 MockUser
。
这是一个错误吗?还是仅适用于 VS2010/.Net 4.0 的新功能?
更新: 这不是错误,我没有按照我的意思指定接口(interface),它应该定义为:
public interface IRepository<T> where T : IModel
{
T Get(int id);
void Update(T item);
int Add(T item);
}
换句话说,我不需要在接口(interface)和方法级别指定 Type 参数 T
,而只需在接口(interface)上指定。
最佳答案
<T>
没有任何意义作为接口(interface)方法的类型参数。这不是必需的,如果您删除它,您将获得预期的行为——除了结果是这样的:
public class MockRepository : IRepository<IModel>
{
public IModel Get(int id)
{
throw new NotImplementedException();
}
public void Update()
{
throw new NotImplementedException();
}
public int Add(IModel item)
{
throw new NotImplementedException();
}
}
通用方法类型参数不同于接口(interface)/类类型参数——我不希望它们使用 IModel
实现在你的例子中。 (换句话说,IRepository<T>
中的 T 不是 Get<T>
中的 T。)
关于c# - VS2010实现通用接口(interface)扩展不使用指定类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2643035/