鉴于结构:structure box_dimensions: int? left int? right int? top int? bottom point? top_left point? top_right point? bottom_left point? bottom_right point? top_center point? bottom_center point? center_left point? center_right point? center int? width int? height rectangle? bounds每个字段是否可以定义。你将如何实现这个功能?如果没有足够的字段定义来描述一个框,或者定义的字段太多,则该函数应该返回一个错误。如果输入是一致的,它应该计算未定义的字段。你可以用一个盒子的中心、宽度和高度,或者左上角和右下角等来描述它我能想到的唯一解决办法就是找到很多其他的办法。我相信有个聪明的办法。编辑如果你想知道我怎么会有这样的结构,这就是为什么:我在玩弄“按约束布局”系统的想法:用户定义一组框,并为每个框定义一组约束,如“box_a.top_left=box_b.bottom_right”、“box_a.width=box_b.width/2”。真正的结构字段实际上是表达式AST,而不是值。所以我需要检查一个框是“欠约束”还是“过约束”,如果可以,从给定的框中创建缺少的表达式AST。 最佳答案 是的,当然会有太多的if-elses。我试图让他们保持合理的组织:howManyLefts = 0if (left is set) { realLeft = left; howManyLefts++; }if (top_left is set) { realLeft = top_left.left; howManyLefts++; }if (bottom_left is set) { realLeft = bottom_left.left; howManyLefts++; }if (center_left is set) { realLeft = center_left.left; howManyLefts++; }if (bounds is set) { realLeft = bounds.left; howManyLefts++; }if (howManyLefts > 1) return error;现在,对center、right和width重复该代码块。现在您将得到howManyLefts、howManyCenters、howManyRights和howManyWidths,所有这些值要么是零,要么是一,这取决于是否提供了值您只需要设置两个值和两个未设置值,因此:if (howManyLefts + howManyRights + howManyCenters + howManyWidths != 2) return errorif (howManyWidths == 0){ // howManyWidths is 0, so we look for the remaining 0 and assume the rest is 1s if (howManyCenters == 0) { realWidth = realRight - realLeft; realCenter = (realRight + realLeft) / 2; } else if (howManyLefts == 0) { realWidth = 2 * (realRight - realCenter); realLeft = realRight - realWidth; } else { realWidth = 2 * (realCenter - realLeft); realRight = realLeft + realWidth; }}else{ // howManyWidths is 1, so we look for the remaining 1 and assume the rest is 0s if (howManyCenters == 1) { realLeft = realCenter - realWidth / 2; realRight = realCenter + realWidth / 2; } else if (howManyLefts == 1) { realRight = realLeft + realWidth; realCenter = (realRight + realLeft) / 2; } else { realLeft = realRight - realWidth; realCenter = (realRight + realLeft) / 2; }}现在,重复所有的垂直轴(即替换{,left,center,right },{{cc>,width,top,center }。
10-06 10:42