簡體   English   中英

輸入的字符串格式不正確。 處理異常

[英]Input string was not in correct format. Handle exception

我收到異常“輸入字符串的格式不正確”。 我想處理該異常並添加我自己的錯誤。 輸入應為int。 我應該在哪里做? 我有一個帶listview的objectdatasource,並且在從后面的代碼獲取textbox.text時遇到麻煩,因此可以使用tryParse。

您的媒體資源為Int32類型。 您不能為該屬性分配除有效整數以外的任何內容。 現在,如果您有一些字符串形式的用戶輸入,然后需要將其分配給integer屬性,則可以使用int.TryParse方法來確保用戶輸入的值是有效的整數。

例如:

string someValueEnteredByUser = ...
int value;
if (!int.TryParse(someValueEnteredByUser, out value))
{
    // the value entered by the user is not a valid integer
}
else
{
    // the value is a valid integer => you can use the value variable here
}

Number 始終是一個int ,它的定義方式是...

您可能想要驗證字符串的內容。 最簡單的方法是將其解析為一個int

int number;

if(!int.TryParse(yourString, out number))
{
   Not an int!
}

“值”將始終與變量屬於同一類型。 因此具有:

private bool mabool = false; 

public bool MaBool
{
    get { return mabool; }
    set { mabool = value; }
}

永遠不會崩潰。 正如我所說,這是因為值將是變量的相同類型。 在這種情況下,value是布爾值。

嘗試上課:

public class Rotator
{
    public Roll, Pitch, Yaw;

    // Declarations here (...)
}

private Rotator rotation = new Rotator();
public Rotator Rotation
{
    get { return rotation; }
    set
    {
        // Since value is of the same type as our variable (Rotator)
        // then we can access it's components.
        if (value.Yaw > 180) // Limit yaw to a maximum of 180°
            value.Yaw = 180;
        else if (value.Yaw < -180) // Limit yaw to a minimum of -180°
            value.Yaw = -180;

        rotation = value;
    }
}

如第二個示例所示,value是Rotator,因此我們可以訪問它的組件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM