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

标签 c# generics

我在 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/

相关文章:

c# - 尝试将大 Excel 文件读入 DataTable 时出现 OutOfMemoryException

c# - 枚举和常量。什么时候使用哪个?

c# - 实现 operator== 时如何避免 NullReferenceException

C# 泛型方法,new() 构造函数约束中的类型参数

c# - 如何将 "any non-nullable type"指定为泛型类型参数约束?

C# 实用功能静态方法/静态类/单例模式

generics - 使用泛型存储和生成类的实例

c# - 简化 C# 中的循环泛型约束?

c# - 从类型创建通用变量 - 如何?或者将 Activator.CreateInstance() 与属性 { } 而不是参数 ( ) 一起使用?

c# - 如何在Windows 7下 "Install"/"Enable".Net 3.5 SP1?