我如何定义检查整数列表 [英] How can i define a List of checked integers

查看:127
本文介绍了我如何定义检查整数列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有列表中所定义的整数和清单; INT> myIntList =新的List< INT>(); 像往常一样,我会增加价值,使用 myIntList.Add()方法列表。我现在面临的问题是,在该列表中的值是动态的(一些计算的结果),可能会超过一个整数可以容纳的最大值。



考虑以下场景:

  INT X = int.MaxValue; 
myIntList.Add(X + 1);

这将增加 -2147483648 到列表而不是抛出一个异常。我需要在这里抛出异常。我知道 myIntList.Add(检查(X + 1)); 将完美地胜任这份工作我甚至可以在附上myIntList.Add()检查{} 这样的:

 检查
{
myIntList。加(12);
myIntList.Add(int.MaxValue);
myIntList.Add(X + 1);
}



这里是我的问题有没有替代方案这个?我可以定义检查整数列表?我怎样才能让抛出在添加到列表中的数值超过了限制



更新的情况下的例外列表:



感谢大家的响应,你最人的建议(如果它的边界之外抛出异常),将它们添加到列表中前检查整数。这是相同的是我通过给定片断托运{//添加元素}完成会抛出异常,没有任何复杂的条件检查。


< DIV CLASS =h2_lin>解决方案

您解决在错误的级别问题。首先,你的计算 - 它返回某种类型的价值 - INT 等,是不是应该有检查溢出?难道没有溢出,但回报率,例如?



如果这还应该同时增加了完成容器,您可以创建检查表是这样的:

 类CheckedList:列表< INT> 
{
公共无效添加(长x)
{
如果(int.MaxValue< X || int.MinValue> X)抛出新ArgumentOutOfRangeException(无效) ;
变种I =(INT)x;
base.Add(ⅰ);
}
}


I have a List of Integers defined as List<int> myIntList = new List<int>(); As usual I will add value to the list using myIntList.Add() method. The problem I am facing is that the values in the list are dynamic(result of some calculation) that may exceed the maximum value that an integer can hold.

Consider the following scenario:

 int x = int.MaxValue;
 myIntList.Add(x + 1); 

This will add -2147483648 to the list instead of throwing an exception. I need to throw an exception here. I know myIntList.Add(checked(x + 1)); will do the job perfectly or I can even enclose the myIntList.Add() within checked{} like the following:

 checked
     {
         myIntList.Add(12);
         myIntList.Add(int.MaxValue);
         myIntList.Add(x + 1);
     }

Here is my question Is there any alternative for this? Can I define a list of checked integers? How can I make a list that throws an exception in the case where the value added to the list exceeds the limit?

Updates:

Thank you all for the response, most of you people suggest to check the integer (Throw exception if it outside the boundary) before adding them to the list. This is the same what i done through the given snippet checked{// add elements } it will throw exception without any complex condition checking.

解决方案

You are solving the problem on the wrong level. First of all, your calculation - it returns the value of some type - int, long etc. Should not it be there checked for the overflow? Is it not overflowed, but returns long, for example?

If this still should be done while adding to the container, you can create your check list like this:

class CheckedList : List<int>
{
    public void Add(long x)
    {
        if (int.MaxValue < x || int.MinValue > x) throw new ArgumentOutOfRangeException("Invalid");
        var i = (int) x;
        base.Add(i);
    }
}

这篇关于我如何定义检查整数列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆