如何删除 c# 类中的重复代码
本文关键字:代码 何删除 删除 | 更新日期: 2023-09-27 18:33:50
请帮助我重构以下代码方案
我有两个班级
class Example1
{
public string username {private get;set;}
public string password {private get;set;}
public obj[] callfunction(string value) {//code}
}
class Example2
{
public string UserName {private get;set;}
public string Password {private get;set;}
public List<ObjectDefinition> function1(string option)
{
Example1 obj = new Example1();
obj.username = this.UserName ;
obj.password = this.Password;
obj.callfunction(option)
//Other codes
}
public List<ObjectDefinition> function2(string option,string other,string other_more_params)
{
Example1 obj = new Example1();
obj.username = this.UserName ;
obj.password = this.Password;
obj.callfunction(other)
//Other codes
}
public List<ObjectDefinition> function3(string option)
{
Example1 obj = new Example1();
obj.username = this.UserName ;
obj.password = this.Password;
obj.callfunction(option)
//Other codes
}
//so on
}
所以我的问题是声明这个重复对象声明的最佳方法是什么。
添加一个函数来创建Example1
class Example2
{
public string UserName {private get;set;}
public string Password{private get;set;}
public List<ObjectDefinition> function1(string option)
{
var example1 = CreateExample1(option);
example1.callfunction(option);
//Other codes
}
public List<ObjectDefinition> function2(string option,string other,string other_more_params)
{
var example1 = CreateExample1(option);
example1.callfunction(option);
//Other codes
}
public List<ObjectDefinition> function3(string option)
{
var example1 = CreateExample1(option);
example1.callfunction(option);
//Other codes
}
//so on
public Example1 CreateExample1(string option)
{
Example1 obj=new Example1();
obj.username =this.UserName ;
obj.password=this.Password;
return obj;
}
}
如何定义一个函数,该函数将使用所需的用户名和密码返回示例 1 的实例:
class Example1
{
public string username {private get;set;}
public string password{private get;set;}
public obj[] callfunction(string value){//code}
}
class Example2
{
public string UserName {private get;set;}
public string Password{private get;set;}
public List<ObjectDefinition> function1(string option)
{
Example1 obj=GetExample1Instance();
obj.callfunction(option)
//Other codes
}
public List<ObjectDefinition> function2(string option,string other,string other_more_params)
{
Example1 obj=GetExample1Instance();
obj.callfunction(other)
//Other codes
}
public List<ObjectDefinition> function3(string option)
{
Example1 obj=GetExample1Instance();
obj.callfunction(option)
//Other codes
}
private Example1 GetExample1Instance()
{
return new Example1 { username = this.UserName, password = this.Password }
}
//so on
}
或者,您可以考虑简单地将示例 1 的实例作为示例 2 中的成员(假设所需的功能支持此功能)。