我想将两个功能结合在一起,然后再使用,以便遵循干式代码的SOLID原则。我有两个不同的列表,都包含id作为其对象的属性。我想组合此逻辑并给另一个方法参数,以便它将执行重复的逻辑。
public static bool IsParfumesStyleValid(string style, List<Parfumes> parfumes)
{
foreach (var parfume in parfumes)
{
var matchNumbersInDecimal = Regex.IsMatch(parfume.Id, "^(\\d*\\.)\\d+");
var matchFullNumbers = Regex.IsMatch(parfume.Id, "^\\d+$");
var matchNumbersWithHalfs = Regex.IsMatch(parfume.Id, "^[1-9][0-9]*\\/[1-9][0-9]*");
if ((style == "decimal" && !matchNumbersInDecimal)
|| (style == "full" && !matchFullNumbers)
|| (style == "numbersWithHalfs" && !matchNumbersWithHalfs))
{
return false;
}
}
return true;
}
public static bool IsCosmeticsStyleValid(string style, List<Cosmetics> cosmetics)
{
foreach (var item in cosmetics)
{
var matchNumbersInDecimal = Regex.IsMatch(item.Id, "^(\\d*\\.)\\d+");
var matchFullNumbers = Regex.IsMatch(item.Id, "^\\d+$");
var matchNumbersWithHalfs = Regex.IsMatch(item.Id, "^[1-9][0-9]*\\/[1-9][0-9]*");
if ((style == "decimal" && !matchNumbersInDecimal)
|| (style == "full" && !matchFullNumbers)
|| (style == "numbersWithHalfs" && !matchNumbersWithHalfs))
{
return false;
}
}
return true;
}
Run Code Online (Sandbox Code Playgroud)
我的建议现在不起作用,看起来像这样。
public static bool IsObjectsStyleValid(string style, List<Cosmetics> cosmetics,List<Parfumes> parfumes)
{
var list;
if (parfumes == null)
{
list = cosmetics;
}
else
{
list = parfumes;
}
foreach (var item in list)
{
var matchNumbersInDecimal = Regex.IsMatch(item.Id, "^(\\d*\\.)\\d+");
var matchFullNumbers = Regex.IsMatch(item.Id, "^\\d+$");
var matchNumbersWithHalfs = Regex.IsMatch(item.Id, "^[1-9][0-9]*\\/[1-9][0-9]*");
if ((style == "decimal" && !matchNumbersInDecimal)
|| (style == "full" && !matchFullNumbers)
|| (style == "numbersWithHalfs" && !matchNumbersWithHalfs))
{
return false;
}
}
return true;
}
Run Code Online (Sandbox Code Playgroud)
有人可以给我适当的例子吗?
如果您可以控制Cosmetics和Parfumes类,那么我会让它们都实现带有公共字符串Id属性的接口:
interface IHaveId
{
string Id {get;}
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以执行以下操作,几乎无需更改已发布的代码:
public static bool IsStyleValid<T>(string style, List<T> product)
where T : IHaveId
{
foreach (var item in product)
{
var matchNumbersInDecimal = Regex.IsMatch(item.Id, "^(\\d*\\.)\\d+");
var matchFullNumbers = Regex.IsMatch(item.Id, "^\\d+$");
var matchNumbersWithHalfs = Regex.IsMatch(item.Id, "^[1-9][0-9]*\\/[1-9][0-9]*");
if ((style == "decimal" && !matchNumbersInDecimal)
|| (style == "full" && !matchFullNumbers)
|| (style == "numbersWithHalfs" && !matchNumbersWithHalfs))
{
return false;
}
}
return true;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
70 次 |
| 最近记录: |