@jvbsl Ich habe deine Loesung noch um den MinValue check erweitert, der hat noch gefehlt:
Mich wuerde trotzdem brennend interessieren wie man das noch erweitern kann das auch floatingpoint operations unterstuetzt werden, d.h.
C#-Quellcode
- internal class Program
- {
- public static void Main(string[] args)
- {
- Console.WriteLine(Limits<long>.IsOverflowing(long.MinValue, (long) -10)); // true
- Console.WriteLine(Limits<long>.IsOverflowing(long.MaxValue, (long) 10)); // true
- Console.WriteLine(Limits<long>.IsOverflowing(long.MaxValue - 12, (long) 10)); // false
- Console.WriteLine(Limits<int>.IsOverflowing(int.MinValue, (int) -10)); // true
- Console.WriteLine(Limits<int>.IsOverflowing(int.MaxValue, (int) 10)); // true
- Console.WriteLine(Limits<int>.IsOverflowing(int.MaxValue - 5, (int) 2)); // false
- Console.WriteLine(Limits<long>.IsOverflowing(short.MinValue, (short) -10)); // true
- Console.WriteLine(Limits<long>.IsOverflowing(short.MaxValue, (short) 10)); // true
- Console.WriteLine(Limits<long>.IsOverflowing(short.MaxValue - 10, (short) 8)); // false
- }
- }
- static class Limits<T> where T : struct
- {
- private static readonly T MaxValue;
- private static readonly T MinValue;
- static Limits()
- {
- var type = typeof(T);
- var fld = type.GetField("MaxValue", BindingFlags.Public | BindingFlags.Static);
- if (fld != null)
- MaxValue = (T) fld.GetValue(null);
- fld = type.GetField("MinValue", BindingFlags.Public | BindingFlags.Static);
- if (fld != null)
- MinValue = (T) fld.GetValue(null);
- }
- public static bool IsOverflowing<T>(T a, T b) where T : struct
- {
- decimal v1 = (decimal) Convert.ChangeType(a, typeof(decimal));
- decimal v2 = (decimal) Convert.ChangeType(b, typeof(decimal));
- decimal maxVal = (decimal) Convert.ChangeType(Limits<T>.MaxValue, typeof(decimal));
- decimal minVal = (decimal) Convert.ChangeType(Limits<T>.MinValue, typeof(decimal));
- return (v1 + v2) > maxVal || (v1 + v2) < minVal;
- }
- }
Mich wuerde trotzdem brennend interessieren wie man das noch erweitern kann das auch floatingpoint operations unterstuetzt werden, d.h.
float
und double
.C# Developer
Learning C++
Learning C++