【发布时间】:2014-03-24 02:29:56
【问题描述】:
想象一下有这样一个简单的方法:
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) 语法编写此代码?如果您有更好的建议,我将很高兴听到。
如果不可能,是否可以用macro 包裹它?(就像我们写C 时经常做的那样)
告诉我任何可能的删除重复代码的想法:)
【问题讨论】:
-
不幸的是,这看起来并不容易:stackoverflow.com/questions/1867482/…
-
@Matthew 谢谢。问题稍作修改。
-
C# 中没有宏。
标签: c# reflection refactoring c#-5.0 code-duplication