方法中的临时方法
本文关键字:方法 | 更新日期: 2023-09-27 18:19:22
在下面的方法中,有三个条件。我想用一个方法替换它们,并传递条件。
同样,条件体几乎是重复的。是否有可能在MyMethod()中创建一个只存在于本地的方法?下面的代码简化成这样:
//减少代码public ClassZ MyMethod (Class1 class1Var, Class2 class2Var)
{
return localMethod((class1Var.SomeBool && !class2Var.SomeBool), false, "This is string1");
return localMethod((class1Var.SomeBool && !class2Var.IsMatch(class2Var)), true);
return localMethod((class1Var.SomeProperty.HasValue && !class2Var.SomeBool), false, "This is string2");
//...localMethod() defined here...
}
但是在上面的例子中,只有一个应该返回。
原始代码//
public ClassZ MyMethod (Class1 class1Var, Class2 class2Var)
{
if(class1Var.SomeBool && !class2Var.SomeBool)
{
return new ClassZ
{
Property1 = false,
String1 = "This is string1"
};
}
if(class1Var.SomeBool && !class2Var.IsMatch(class2Var))
{
return new ClassZ
{
Property1 = true,
};
}
if(class1Var.SomeProperty.HasValue && !class2Var.SomeBool)
{
return new ClassZ
{
Property1 = false,
String1 = "This is string2"
};
}
}
基本上,我想在一个方法中创建一个临时方法
您可以使用Func
表示法。Funcs
封装委托方法。阅读Funcs
的文档在这里。对于具有n
泛型参数的Func
,第一个n-1
是方法的输入,最后一个参数是返回类型。试试这样做:
public ClassZ MyMethod (Class1 class1Var, Class2 class2Var)
{
Func<bool, bool, string, ClassZ> myFunc
= (predicate, prop1Value, string1Value) =>
predicate
? new ClassZ { Property1 = prop1Value, String1 = string1Value }
: null;
return myFunc((class1Var.SomeBool && !class2Var.SomeBool), false, "This is string1")
?? myFunc((class1Var.SomeBool && !class2Var.IsMatch(class2Var)), true)
?? myFunc((class1Var.SomeProperty.HasValue && !class2Var.SomeBool), false, "This is string2");
}
在这里,我们实例化了一个Func
,它接受一个bool
(谓词),要设置的参数(第二个bool
和string
),并返回一个ClassZ
。
这也使用空合并(??
表示法),它返回第一个非空参数。在这里阅读更多关于null合并的信息。
另一个选择是使用Actions
,它封装了void
方法。点击这里阅读Actions
。您可以实例化一个新的ClassZ
,然后在其上调用3 Actions
,这将有条件地设置所提供的变量。
public ClassZ MyMethod (Class1 class1Var, Class2 class2Var)
{
Action<bool, bool, string, ClassZ> myAction
= (predicate, prop1Value, string1Value, classZInstance) =>
if (predicate)
{
classZIntance.Property1 = prop1Value;
classZInstance.String1 = string1Value;
}
var myClassZ = new ClassZ();
myAction((class1Var.SomeBool && !class2Var.SomeBool), false, "This is string1", myClassZ)
myAction((class1Var.SomeBool && !class2Var.IsMatch(class2Var)), true, classZ)
myAction((class1Var.SomeProperty.HasValue && !class2Var.SomeBool), false, "This is string2", myClassZ);
return myClassZ;
}