我目前有一个方法,我正在硬编码需要在if语句中验证的值,然后运行与我正在硬编码的名称匹配的方法。 这是我的代码
public Class Name
public static Dictionary<string, ValueMap> Name1= new Dictionary<string, ValueMap>
public static Dictionary<string, ValueMap> Name2= new Dictionary<string, ValueMap>
public Class compare
public string Test (string sample, string Name)
{
if (sample == "Name1")
{
var results = MethodName (sample, Name.Name1);//call method name Name1
return "";
}
if (sample == "Name2")
{
var results = MethodName (sample, Name.Name2); //call method name Name2
return "";
}
if (sample == "Name3")
{
var results = MethodName (sample, Name.Name3); //call method name Name3
return "";
}
else
{
return ""; ;
}
}
我不想每次都需要在MethodName中添加其他方法或对if语句中的值进行硬编码时添加if语句,所以我想知道是否有一种方法可以只在内部查找方法匹配字符串样本并将此方法传递给我的var结果的比较类= MethodName(样本,Name.Name3);
像这样的例子
public Class Name
public static Dictionary<string, ValueMap> Name1= new Dictionary<string, ValueMap>
public static Dictionary<string, ValueMap> Name2= new Dictionary<string, ValueMap>
public Class Test
string sample = Name1
public string Test (string sample, string Name, Name name)
{
var results = MethodName (sample, Name1 -pass the method inside the compare class that match the name inside the sample string );
return "";
}
else
{
return sample name was not found ; ;
}
答案 0 :(得分:-2)
一个答案是使用开关盒。 第二个是使用“责任变更”模式。 责任链代替if条款。