我有2个函数执行相同的操作; 因为底层API有一个重载函数,它接受一个字符串或一个int.
由于我正在使用此函数,我需要使用字符串或int调用该函数.超载是唯一的方法吗?我复制代码,除了函数的签名; 而且似乎浪费了代码.
public void taketwo(int value1, int value2)
{
// Other operations happen here
baseAPI.getvalues(value1, value2);
}
public void taketwo(string val1_str, string val2_str)
{
// Other operations happen here
baseAPI.getvalues(val1_str, val2_str);
}
Run Code Online (Sandbox Code Playgroud)
我记得有关通用功能的事情; 但我不确定这是否适用于这种情况; 我以前从未使用它们,在潜入之前,我认为首先要问一下这个问题.
你可以在这里使用动态类型:
// I don't recommend you do this - see later
public void TakeTwo(dynamic value1, dynamic value2)
{
baseAPI.GetValues(value1, value2);
}
Run Code Online (Sandbox Code Playgroud)
GetValues然后将在执行时执行调用的重载决策.
然而:
TakeTwo是否有效您谈到复制代码,但在示例中,您已经显示所有代码都是方法调用.如果方法中的其他代码真的很常见,我建议在两个重载中提取该公共代码并调用它:
public void TakeTwo(int value1, int value2)
{
CommonCode();
baseAPI.GetValues(value1, value2);
}
public void TakeTwo(string value1, string value2)
{
CommonCode();
baseAPI.GetValues(value1, value2);
}
private void CommonCode()
{
// Things you want to do in both methods
}
Run Code Online (Sandbox Code Playgroud)