如何使用单位类型的值执行数学运算?

时间:2014-06-25 13:03:52

标签: c# asp.net types

我有三个变量(asp.net中不同控件的宽度)。他们的类型是Unit

我想做以下行动。例如:

Contol1.Width = Control2.Width - Control3.Width

现在我收到一个错误:

  

无法将操作符“ - ”应用于“System.Web.UI.WebControls.Unit”类型的操作数。

如何使用此值执行数学运算?

2 个答案:

答案 0 :(得分:5)

System.Web.UI.WebControls.Unit是一个可以使用Value-property的结构。

Contol1.Width.Value - Control2.Width.Value - Control3.Width.Value

答案 1 :(得分:2)

已经说过你可以使用Unit类的Value属性,但是你不应该忘记某些控件可能有不同的measures

如果一个控件的大小以像素为单位测量,而其他控件的大小以点为单位怎么办?

public Unit Subtract(this Unit unit, Unit toSubtract)
{
    if (unit.Type != toSubtract.Type)
        throw new InvalidOperationException("Types are not compatible");

    return new Unit(unit.Value - toSubtract.Value, 
       unit.Type);
}

...

control1.Width = control2.Width.Subtract(control3.Width);

如果您的控件不是那么简单但更安全。措施是不相容的。如果你有时间,你可以添加一些转换逻辑来代替异常抛出。