你會如何重構這兩個類來抽象出相似之處?抽象類?簡單的繼承?重構類(es)看起來像什麼?重構兩個基本類
public class LanguageCode
{
/// <summary>
/// Get the lowercase two-character ISO 639-1 language code.
/// </summary>
public readonly string Value;
public LanguageCode(string language)
{
this.Value = new CultureInfo(language).TwoLetterISOLanguageName;
}
public static LanguageCode TryParse(string language)
{
if (language == null)
{
return null;
}
if (language.Length > 2)
{
language = language.Substring(0, 2);
}
try
{
return new LanguageCode(language);
}
catch (ArgumentException)
{
return null;
}
}
}
public class RegionCode
{
/// <summary>
/// Get the uppercase two-character ISO 3166 region/country code.
/// </summary>
public readonly string Value;
public RegionCode(string region)
{
this.Value = new RegionInfo(region).TwoLetterISORegionName;
}
public static RegionCode TryParse(string region)
{
if (region == null)
{
return null;
}
if (region.Length > 2)
{
region = region.Substring(0, 2);
}
try
{
return new RegionCode(region);
}
catch (ArgumentException)
{
return null;
}
}
}
不幸的是,這不會很好,因爲你的TryParse方法不是靜態的。 TryParse是一個有效的工廠方法,它返回一個新的LanguageCode或RegionCode對象。在你的例子中,你需要先創建一個對象。你不能重寫基礎TryParse,因爲它是靜態的。 – 2008-09-16 09:28:04