【问题标题】:Input string was not in correct format. Handle exception输入字符串的格式不正确。处理异常
【发布时间】:2012-04-02 11:38:55
【问题描述】:

我收到异常“输入字符串的格式不正确”。我想处理那个异常并添加我自己的错误。输入应该是一个 int。我应该在哪里做这个?我有一个带有 listview 的 objectdatasource,我无法从后面的代码中获取 textbox.text,因此我可以使用 tryParse。

【问题讨论】:

  • 这不是验证。如果该值错误,则永远不应像您在代码中那样设置它。
  • 此属性已接受 INT。 “验证”是什么意思?
  • 你认为它会是什么?除了int
  • @leppie:这是非常好的 ViewModel 代码。

标签: c# validation properties


【解决方案1】:

您的属性是 Int32 类型。除了有效整数之外,您不能将任何其他内容分配给此属性。现在,如果您有一些字符串形式的用户输入,然后您需要将其分配给整数属性,您可以使用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
}

【讨论】:

  • 假设这是关于负面/非负面的东西。但是控制已经完成了......呸。
【解决方案2】:

Number总是int,它是这样定义的...

您可能想要验证字符串的内容。最简单的方法是将其解析为int

int number;

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

【讨论】:

    【解决方案3】:

    'value' 将始终与您的变量具有相同的类型。因此有这个:

    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,因此我们可以访问它的组件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-12
      • 2018-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多