抽象 class 的驱动 class 中的额外方法

Extra methods in drived class of abstract class

我知道这个问题已经被问过很多次了。但是看着答案我找不到合适的或适合我的工作。

假设我有一个摘要class

public abstract class EntityService<T>
{
     public T GetAll()
     {
         //Implementation
     }
}

那我有驱动class

public class UserService : EntityService<User>
{
      public User GetAll(string Orderby)
      {
          //Implementation
      }
}

我创建了一个 UserService 的静态变量,以便在我的项目中使用它。

public static readonly EntityService<User> UserService = new UserService();

使用 UserService.GetAll(); 会非常好。但是,当我想使用 UserService.GetAll("Acsending"); 时,会出现编译器错误,提示此方法不存在。我知道我必须将它转换为 UserService 类型,但我做不到。我放在哪里 (UserService) 它总是出错,我想知道是否有更好的方法来做到这一点而不强制转换它,因为我想尽可能简单明了地编写我的代码。

您需要像这样将变量声明为子类:

public static readonly UserService userService = new UserService();

或者,你每次想使用EntityService<User> as UserService时都垂头丧气:

var userServiceDownCast = (UserService)userService;
userServiceDownCast.GetAll("Ascending");

我认为对于你的情况这样做会有用,抱歉有点晚了,但是:

public interface IUserService
{
    User GetAll();

    User GetAll(string OrderBy);
}

public abstract class EntityService<T>
{
    public T GetAll()
    {
       //Implementation
    }
}

public class UserService : EntityService<User>, IUserService
{
    public User GetAll(string OrderBy) 
    {
       //Implementation
    }
}

然后像这样使用它:

public static readonly IUserService UserService = new UserService();
....
UserService.GetAll();
UserService.GetAll("orderByColumn");

然后如果你想要一些实体的通用代码,你可以这样写:

 void ForEntityMethod(EntityService<T> entityService)

如果对用户有特殊要求,即:

 void ForUserMethod(IUserService userService)

它认为它给了你更多的灵活性,避免在你的情况下施法。 还存在其他好的变体,但如果您对系统有一些未来的愿景,可以使用它们。