C# I';我们有两个函数,只是在某些条件下有所不同。它能统一吗?
所以我有两种方法:C# I';我们有两个函数,只是在某些条件下有所不同。它能统一吗?,c#,dry,C#,Dry,所以我有两种方法: public static string Figure2D() { dynamic shapeValue; do { shapeValue = Presentation.Present(); } while (shapeValue.Is3D); return shapeValue.ToString("R"); } publi
public static string Figure2D()
{
dynamic shapeValue;
do
{
shapeValue = Presentation.Present();
}
while (shapeValue.Is3D);
return shapeValue.ToString("R");
}
public static string Figure3D()
{
dynamic shapeValue;
do
{
shapeValue = Presentation.Present();
}
while (!shapeValue.Is3D);
return shapeValue.ToString("R");
}
它们之间的唯一区别是while条件。如何将这两个函数合并为一个函数?传递参数值可能是必要的,也是可以接受的,但我喜欢保持简短。有什么想法吗?怎么样
public static string Figure(Predicate<dynamic> p)
{
dynamic shapeValue;
do
{
shapeValue = Presentation.Present();
}
while (p(shapeValue));
return shapeValue.ToString("R");
}
公共静态字符串图(谓词p)
{
动态形态价值;
做
{
shapeValue=Presentation.Present();
}
而(p(shapeValue));
返回shapeValue.ToString(“R”);
}
怎么样
public static string Figure(Predicate<dynamic> p)
{
dynamic shapeValue;
do
{
shapeValue = Presentation.Present();
}
while (p(shapeValue));
return shapeValue.ToString("R");
}
公共静态字符串图(谓词p)
{
动态形态价值;
做
{
shapeValue=Presentation.Present();
}
而(p(shapeValue));
返回shapeValue.ToString(“R”);
}
@stuartd有一个代码>输入one@stuartd一个是否定的,另一个不是。小文本再次获胜,sorry@stuartd有一个代码>输入one@stuartd一个是否定的,另一个不是。小文本再次获胜,所以我建议使用Func
而不是Predicate
,这样它就可以简单地用作Figure(thing=>!thing.Is3D)
Hmm,什么是Predicate,我如何传递条件?(抱歉,对C#来说有点陌生)@Jesper:它是一个返回bool的委托(与Func相反,Func返回您指定的任何内容)。本质上,谓词===Func。。有关更多信息,请查看MSDN或intellisense中的VS.@quetzalcatl.dynamic不能用于lambda@quetzalcoatl但是在这里使用Func
比使用Predicate
有什么好处呢Predicate
也可以简单地使用Figure(p=>p.Is3D)
调用Func
而不是Predicate
,因此它可以简单地用作Figure(thing=>!thing.Is3D)
Hmm,什么是谓词,我如何传递条件?(抱歉,对C#来说有点陌生)@Jesper:它是一个返回bool的委托(与Func相反,Func返回您指定的任何内容)。本质上,谓词===Func。。有关更多信息,请查看MSDN或intellisense中的VS.@quetzalcatl.dynamic不能用于lambda@quetzalcoatl但是在这里使用Func
比使用Predicate
有什么好处呢<代码>谓词
也可以使用Figure(p=>p.Is3D)