gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 21:56:40 24 4
gpt4 key购买 nike

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

假设我有一个抽象类

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com