c# - 抽象类的派生类中的额外方法

标签 c# inheritance abstract

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

假设我有一个抽象类

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

那我有驾校

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 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)

它认为它可以为您提供更大的灵 active ,并避免在您的情况下强制转换。 还存在其他好的变体,但如果您对系统有一些 future 的愿景,则可以使用它们。

关于c# - 抽象类的派生类中的额外方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31349271/

相关文章:

php - 如何获取调用类的名称(在 PHP 中)

java - 抽象类和方法,为什么?

julia - 是否可以从 Julia 中的覆盖函数中调用重载函数?

c# - Path.Combine 背后究竟发生了什么

c# - 如何使用 C# 在 SQL Server 数据库中存储哈希值?

c# - Azure 服务总线序列化类型

c# - 单击 winform 应用程序中的按钮后,如何将焦点返回到上次使用的控件?

c++ - 错误 C2660 : 'Aba::f' : function does not take 0 arguments

c++ - 从另一个类创建特定于另一个类的类的优雅/有效方法

c# - C#中的静态成员继承