[英]How to return instance of concrete class from method with generic return type
[英]how to reference the Type in the Concrete class of a generic class
我找到了以下示例,对此我有一个后续问题。
问题中的现有代码是
public interface IRepository<T> where T : EntityObject
{
RepositoryInstructionResult Add(T item);
RepositoryInstructionResult Update(T item);
RepositoryInstructionResult Delete(T item);
}
public class Repository<T> : IRepository<T> where T : EntityObject
{
virtual RepositoryInstructionResult Add(T item)
{ //implementation}
virtual RepositoryInstructionResult Update(T item);
{ //implementation}
virtual RepositoryInstructionResult Delete(T item);
{ //implementation}
}
public class BarRepository : Repositorybase<Bar>
{
public override RepositoryInstructionResult Update(Bar item);
{
//Call base method if needed
//Base.Update(item);
//implement your custom logic here
}
}
我想做的是将 Update 方法更改为类似
public class BarRepository : Repositorybase<Bar>
{
// T is of Type Bar
public override RepositoryInstructionResult Update(T item);
{
//implement your custom logic here
}
}
问题:有没有办法将BarResposity: Repositorybase<Bar>
中的泛型类型暴露给 BarRepository 中的方法?
在构建具体的 class 时寻找“搜索和替换”的更好替代方法(例如,将 BarRespository 复制为 FooRepository 并将所有引用从 Bar 更改为 Foo)。 我宁愿只在一个地方改变类型。
(编辑)使用需要保持为
var obj = new BarRepository();
但这有什么问题
public class BarRepository<T> : Repository<Bar> where T : class
{
public override void Update(Bar item)
{
}
public void Update(T item)
{
}
}
这有点 hack,但您可以使用using
别名来定义实体类型:
using MyType = Bar;
public class BarRepository : Repositorybase<MyType>
{
public override RepositoryInstructionResult Update(MyType item);
{
return base.Update(item);
}
}
现在,当您复制到Foo.cs
时,您只需将 using 指令更改为
using MyType = Foo;
但是,我会尝试尽可能多地重用通用代码,因为仅通过查看方法就不清楚MyType
是什么。 find.replace 定义自定义操作的新存储库类型没有任何问题 - 您只想将重复保持在最低限度。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.