繁体   English   中英

如何在通用 class 的具体 class 中引用类型

[英]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();

就像一个注释,如果你要覆盖所有的 Add/Update/Delete ,你可以在 RepositoryBase 中将它们作为抽象,然后 vs 建议是你的朋友: 在此处输入图像描述

如果所有具体类之间存在共享逻辑,则可以将其放在抽象 class 中,并改写抽象受保护方法。

但这有什么问题

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM