C# Werte Typen - Ist dies ein Compiler -Fehler?
Posted: 20 May 2025, 15:16
Nehmen wir an, wir streifen eine Erweiterungsmethode, um ABS als Mitglied von Inumber < /p>
freizulegenpublic static class MathIntExtensions
{
///
/// Exposes Abs as extension method for all INumberBase types.
///
///
///
///
public static TIn Abs(this TIn number)
where TIn : INumber
{
var a = TIn.Abs(number);
return a; // if you call -4.Abs() a will be 4 here - not minus 4
}
}
< /code>
Schauen Sie sich jetzt diesen Testcode an: < /p>
///
var x=int.Abs(-4); // x is now 4
var a=-4;
var b=a.Abs(); // b is now 4 as one would expect
// but this is strangely does not work!
var c=-4.Abs(); // c is now -4 but! - not a expected +4!
< /code>
Warum ist das so? Ich verstehe es nicht. Dies ist extrem kontrastiv.
freizulegenpublic static class MathIntExtensions
{
///
/// Exposes Abs as extension method for all INumberBase types.
///
///
///
///
public static TIn Abs(this TIn number)
where TIn : INumber
{
var a = TIn.Abs(number);
return a; // if you call -4.Abs() a will be 4 here - not minus 4
}
}
< /code>
Schauen Sie sich jetzt diesen Testcode an: < /p>
///
var x=int.Abs(-4); // x is now 4
var a=-4;
var b=a.Abs(); // b is now 4 as one would expect
// but this is strangely does not work!
var c=-4.Abs(); // c is now -4 but! - not a expected +4!
< /code>
Warum ist das so? Ich verstehe es nicht. Dies ist extrem kontrastiv.