私は次の表現を持っています
int someNumber = somevalue;
ConstantExpression expr = Expression.Constant(someNumber);
expr < 0 または expr が負の数かどうかを確認する方法はありますか?
私は次の表現を持っています
int someNumber = somevalue;
ConstantExpression expr = Expression.Constant(someNumber);
expr < 0 または expr が負の数かどうかを確認する方法はありますか?
定数の型がわかっている場合は、基になる定数値を単純にキャストして分析できます。
ConstantExpression expr = /* ... */;
var intConstant = expr.Value as int?;
if (intConstant < 0) { /* do something */ }
. _ Expression
_ _ _ConstantExpression
型がわからないが、有効な数値型を確認したい場合:
ConstantExpression expr = /* ... */;
if (expr.Value != null && expr.Value.GetType().IsNumericType()) {
// Perform an appropriate comparison _somehow_, but not necessarily like this
// (using Convert makes my skin crawl).
var decimalValue = Convert.ToDecimal(expr.Value);
if (decimalValue < 0m) { /* do something */ }
}
2 番目の例で使用される拡張メソッド:
public static Type GetNonNullableType([NotNull] this Type type)
{
if (type == null)
throw new ArgumentNullException("type");
if (!type.IsGenericType || type.GetGenericTypeDefinition() != typeof(Nullable<>))
return type;
return type.GetGenericArguments()[0];
}
public static bool IsNumericType(this Type type)
{
if (type == null)
throw new ArgumentNullException("type");
type = type.GetNonNullableType();
if (type.IsEnum)
return false;
switch (Type.GetTypeCode(type))
{
case TypeCode.SByte:
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.UInt32:
case TypeCode.Int64:
case TypeCode.UInt64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
}
return false;
}