Представьте, что есть такой простой метод:
public async Task<ValidatePhoneNumberResult> ValidatePhoneNumberAsync(
string phone_number,
string country_code,
string country_iso,
DeviceUuid device_uuid, // DeviceUuid supports his own ToString();
string os_name,
string os_version,
string model,
string screen_resolution,
string sim_operator = "00000",
string is_usim = null
)
{
Uri uri = new Uri(MY_URI);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, uri);
Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add("phone_number", phone_number.ToString());
dic.Add("country_code", country_code.ToString());
dic.Add("country_iso", country_iso.ToString());
dic.Add("os_name", os_name.ToString());
dic.Add("model", model.ToString());
dic.Add("screen_resolution", screen_resolution.ToString());
dic.Add("sim_operator", sim_operator.ToString());
if (is_usim != null)
{
dic.Add("is_usim", is_usim.ToString());
}
request.Content = new FormUrlEncodedContent(dic);
return await GetResult<ValidatePhoneNumberResult>(request);
}
Это мой первый дизайн. С этого момента я сделаю много таких функций. Но в коде есть кое-что, что мне не нравится. Это часть добавления параметров в словарь. Думаю, это явное дублирование кода.
- Все имена параметров используются в качестве ключей словаря.
- И все они будут реализовывать свой собственный метод ToString ().
- Если параметр
null
, его не следует помещать в словарь.
Было бы лучше, если бы он мог:
Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add("phone_number", phone_number.ToString());
dic.Add("country_code", country_code.ToString());
dic.Add("country_iso", country_iso.ToString());
dic.Add("os_name", os_name.ToString());
dic.Add("model", model.ToString());
dic.Add("screen_resolution", screen_resolution.ToString());
dic.Add("sim_operator", sim_operator.ToString());
if (is_usim != null)
{
dic.Add("is_usim", is_usim.ToString());
}
// To
var dic = ExtractParametersAndMakeItAsDictionary();
Как сделать этот код с использованием синтаксиса C # (5.0)? Если у вас есть предложение получше, я буду счастлив услышать его.
Если это невозможно, можно ли обернуть его _4 _? (Как мы часто делали, когда писали C
). Сообщите мне любую возможную идею дедупликации кода: )