我有三個變量(asp.net中不同控件的寬度)。他們的類型是Unit
。如何用單位類型的值執行數學運算?
我想要執行以下操作。例如:
Contol1.Width = Control2.Width - Control3.Width
現在,我得到一個錯誤:
Can't apply operator "-" to operands of type "System.Web.UI.WebControls.Unit".
如何我可以用這個值進行數學運算?
我有三個變量(asp.net中不同控件的寬度)。他們的類型是Unit
。如何用單位類型的值執行數學運算?
我想要執行以下操作。例如:
Contol1.Width = Control2.Width - Control3.Width
現在,我得到一個錯誤:
Can't apply operator "-" to operands of type "System.Web.UI.WebControls.Unit".
如何我可以用這個值進行數學運算?
System.Web.UI.WebControls.Unit
是一個結構,它有一個Value
-property,您可以使用。
Contol1.Width.Value - Control2.Width.Value - Control3.Width.Value
謝謝,它可以幫助我。我只能通過5分鐘才能接受這一點。 :( – AlexAstanin
它已經說過,你可以使用本機類的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);
如果您的控件措施不兼容,它不是那麼清晰和簡單,但更安全。如果您有時間可以添加一些轉換邏輯來代替異常拋出。
您是否試過'Contol1.Width.Value' –
已編輯:對不起,我沒有看到我的錯誤。我想將結果分配給Control1.Width – AlexAstanin