static final int safeAdd(int left, int right)
throws ArithmeticException {
if (right > 0 ? left > Integer.MAX_VALUE - right
: left < Integer.MIN_VALUE - right) {
throw new ArithmeticException("Integer overflow");
}
return left + right;
}
static final int safeSubtract(int left, int right)
throws ArithmeticException {
if (right > 0 ? left < Integer.MIN_VALUE + right
: left > Integer.MAX_VALUE + right) {
throw new ArithmeticException("Integer overflow");
}
return left - right;
}
static final int safeMultiply(int left, int right)
throws ArithmeticException {
if (right > 0 ? left > Integer.MAX_VALUE/right
|| left < Integer.MIN_VALUE/right
: (right < -1 ? left > Integer.MIN_VALUE/right
|| left < Integer.MAX_VALUE/right
: right == -1
&& left == Integer.MIN_VALUE) ) {
throw new ArithmeticException("Integer overflow");
}
return left * right;
}
static final int safeDivide(int left, int right)
throws ArithmeticException {
if ((left == Integer.MIN_VALUE) && (right == -1)) {
throw new ArithmeticException("Integer overflow");
}
return left / right;
}
static final int safeNegate(int a) throws ArithmeticException {
if (a == Integer.MIN_VALUE) {
throw new ArithmeticException("Integer overflow");
}
return -a;
}
static final int safeAbs(int a) throws ArithmeticException {
if (a == Integer.MIN_VALUE) {
throw new ArithmeticException("Integer overflow");
}
return Math.abs(a);
}
Две опции:
default(T)
, что означает, что Вы возвратитесь null
, если T будет ссылочным типом (или nullable тип значения), 0
для int
, '\0'
для char
, и т.д. ( таблица Значений по умолчанию (Ссылка C#) ) where T : class
ограничение и затем возвратиться null
как нормальный Ваша другая опция состояла в том, чтобы быть добавить это до конца Вашего объявления:
where T : class
where T: IList
Тот путь это позволит Вам возвращать пустой указатель.
Добавьте ограничение класса как первое ограничение к Вашему универсальному типу.
static T FindThing<T>(IList collection, int id) where T : class, IThing, new()
Можно просто скорректировать ограничения:
where T : class
Тогда пустой указатель возврата позволяется.
Возьмите рекомендацию ошибки... и или пользователь default(T)
или new T
.
необходимо будет добавить в сравнении в коде, чтобы гарантировать, что это было допустимое соответствие, если Вы идете тем путем.
Иначе, потенциально считайте выходной параметр для "соответствия найденным".