在 C# 中删除重复代码的最佳方法
Best way to remove duplicated code in C#
什么是简化 class 的最佳方法,其中包含两种方法,它们的工作几乎相似。
enum State
{
Processing, Stoped
}
public static void CheckState(State state, Element elem)
{
if (elem.State == state)
//some work
}
public static void CheckValue(int value, Element elem)
{
if (elem.Value == value)
//some work
}
因此,Element class 的对象有两个不同类型的字段。删除重复代码的最佳方法是什么?
您可以为该条件传递一个函数。传入元素,因为我假设您需要它进行处理。
public static void CheckAndProcess(Func<bool> CheckCondition, Element elem)
{
if (CheckCondition())
{
//some work
}
}
用法:
CheckAndProcess(()=>(elem.State == state), elem);
CheckAndProcess(()=>(elem.Value == value), elem);
你也可以在没有匿名函数的情况下做到这一点:
public static void CheckElement(Element element, State state = null, int? value = null)
{
if ((state != null && element.State == state) || (value != null && element.Value == value.Value))
{
//some work
}
}
用法:
//for state
CheckElement(element, myState);
//or
//for value
CheckElement(element, value: myValue);
什么是简化 class 的最佳方法,其中包含两种方法,它们的工作几乎相似。
enum State
{
Processing, Stoped
}
public static void CheckState(State state, Element elem)
{
if (elem.State == state)
//some work
}
public static void CheckValue(int value, Element elem)
{
if (elem.Value == value)
//some work
}
因此,Element class 的对象有两个不同类型的字段。删除重复代码的最佳方法是什么?
您可以为该条件传递一个函数。传入元素,因为我假设您需要它进行处理。
public static void CheckAndProcess(Func<bool> CheckCondition, Element elem)
{
if (CheckCondition())
{
//some work
}
}
用法:
CheckAndProcess(()=>(elem.State == state), elem);
CheckAndProcess(()=>(elem.Value == value), elem);
你也可以在没有匿名函数的情况下做到这一点:
public static void CheckElement(Element element, State state = null, int? value = null)
{
if ((state != null && element.State == state) || (value != null && element.Value == value.Value))
{
//some work
}
}
用法:
//for state
CheckElement(element, myState);
//or
//for value
CheckElement(element, value: myValue);