gpt4 book ai didi

c# - 我可以使用 C# 泛型来整合这些方法吗?

转载 作者:行者123 更新时间:2023-11-30 20:10:46 25 4
gpt4 key购买 nike

我在 MVC 应用程序的基本 Controller 中有这段代码:

protected LookUpClient GetLookupClient() {
return new LookUpClient(CurrentUser);
}

protected AdminClient GetAdminClient() {
return new AdminClient(CurrentUser);
}

protected AffiliateClient GetAffiliateClient() {
return new AffiliateClient(CurrentUser);
}

protected MembershipClient GetMembershipClient() {
return new MembershipClient(CurrentUser);
}

protected SecurityClient GetSecurityClient() {
return new SecurityClient();
}

protected ChauffeurClient GetChauffeurClient() {
return new ChauffeurClient(CurrentUser);
}

我可以使用通用方法以某种方式合并它吗?

更新:SecurityClient() 的不同构造函数是故意的。它不需要用户。

最佳答案

您可以将它们全部浓缩为:

protected T GetClient<T>(params object[] constructorParams) 
{
return (T)Activator.CreateInstance(typeof(T), constructorParams);
}

调用它使用:

AdminClient ac = GetClient<AdminClient>(CurrentUser);
LookupClient lc = GetClient<LookupClient>(CurrentUser);
SecurityClient sc = GetClient<SecurityClient>();

等等

如果您的所有客户端都使用了 CurrentUser(目前您的示例表明 SecurityClient 没有),您可以从该方法中删除该参数并且只需要:

protected T GetClient<T>()
{
return (T)Activator.CreateInstance(typeof(T), CurrentUser);
}

这简化了您的调用:

AdminClient ac = GetClient<AdminClient>();

但随后您将无法在不需要 CurrentUser 上下文的客户端上使用它...

附录: 回应您关于无参数构造函数要求的评论。我有一些演示代码,我已经测试证明不需要无参数构造函数:

public class UserContext
{
public string UserName { get; protected set; }
public UserContext(string username)
{
UserName = username;
}
}
public class AdminClient
{
UserContext User { get; set; }
public AdminClient(UserContext currentUser)
{
User = currentUser;
}
}
public class SecurityClient
{
public string Stuff { get { return "Hello World"; } }
public SecurityClient()
{
}
}

class Program
{
public static T CreateClient<T>(params object[] constructorParams)
{
return (T)Activator.CreateInstance(typeof(T), constructorParams);
}
static void Main(string[] args)
{
UserContext currentUser = new UserContext("BenAlabaster");
AdminClient ac = CreateClient<AdminClient>(currentUser);
SecurityClient sc = CreateClient<SecurityClient>();
}
}

此代码运行时没有任何异常,将创建没有无参数构造函数的 AdminClient,还将创建只有无参数构造函数的 SecurityClient。

关于c# - 我可以使用 C# 泛型来整合这些方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4618707/

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