我在MVC应用程序的基本控制器中有这个代码:
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);
}
Run Code Online (Sandbox Code Playgroud)
我可以使用通用方法以某种方式合并它吗?
更新:SecurityClient()的不同构造函数是故意的.它不需要用户.
你可以将它们浓缩为:
protected T GetClient<T>(params object[] constructorParams)
{
return (T)Activator.CreateInstance(typeof(T), constructorParams);
}
Run Code Online (Sandbox Code Playgroud)
用它来调用:
AdminClient ac = GetClient<AdminClient>(CurrentUser);
LookupClient lc = GetClient<LookupClient>(CurrentUser);
SecurityClient sc = GetClient<SecurityClient>();
Run Code Online (Sandbox Code Playgroud)
等等
如果您的所有客户端都使用了CurrentUser(目前您的示例表明SecurityClient没有),您可以从方法中删除参数,并且只需:
protected T GetClient<T>()
{
return (T)Activator.CreateInstance(typeof(T), CurrentUser);
}
Run Code Online (Sandbox Code Playgroud)
这简化了您的通话:
AdminClient ac = GetClient<AdminClient>();
Run Code Online (Sandbox Code Playgroud)
但是你失去了在不需要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>();
}
}
Run Code Online (Sandbox Code Playgroud)
此代码运行时没有任何异常,并且将创建没有paremeterless构造函数的AdminClient,并且还将创建仅具有无参数构造函数的SecurityClient.