我正在我的C#应用程序中实现业务逻辑。 我无法将逻辑拟合到一段理智的代码中。 实现的逻辑是这样的:
有一个元素树,比方说:项目,国家,地区,城市。单个项目包含国家/地区。国家/地区包含Regions,Region包含Cities和Cities包含数据条目。我们将根据可用的信息填充数据条目元素。
此外:
Country
,Region
,City
的实现。我的解决方案可行,但它很丑陋并且使用整数来控制应用流程让我感到不安。
如何改进下面的代码段?
Country country = null;
Region region = null;
City city = null;
int level;
if (!IsCityInfoAvailable())
{
// we have to make a new country, region and city
level = 3;
}
else if (!IsRegionInfoAvailable())
{
// we have to make a new country and region
level = 2;
}
else if (!IsCountryRegionAvailable())
{
// we have to make a new country
level = 1;
}
else
{
// we have all the info we need
level = 0;
}
IDataEntryTarget target;
if (level > 0)
{
country = new Country(Project, "Unnamed Country");
target = country;
}
if (level > 1)
{
region = new Region(country, "Unnamed Region", Region.DefaultRegionSettings);
target = region;
}
if (level > 2)
{
city = new City(region, "Unnamed City", 0);
target = city;
}
// ... proceed with data entry code using `target`...
答案 0 :(得分:2)
编辑:尝试这样:我唯一的问题是城市,地区和地区。国家初始化?在Is()方法中?
Func<Country> GetCountry = () => country ?? (country = new Country(Project, "Unnamed Country"));
Func<Region> GetRegion = () => region ?? (region = new Region(GetCountry(), "Unnamed Region", Region.DefaultRegionSettings));
Func<City> GetCity = () => city ?? (city = new City(GetRegion(), "Unnamed City", 0));
IDataEntryTarget target = null;
if (!IsCityInfoAvailable())
{
// we have to make a new country, region and city
target = GetCity();
}
else if (!IsRegionInfoAvailable())
{
// we have to make a new country and region
target = GetRegion();
}
else if (!IsCountryRegionAvailable())
{
// we have to make a new country
target = GetCountry();
}