Generic Digital Type

I have an extension method that takes a parameter T. This parameter is a numeric type, one of the following: byte, short, int, and long.

I need to check if it is T0. How can this be done?

public static void WriteFlaggedValue<T>(this OutPacket outPacket, uint flag, T value, ref uint outputFlag) where T : struct,
      IComparable,
      IComparable<T>,
      IConvertible,
      IEquatable<T>,
      IFormattable
    {
        if (value == 0)
        {

        }

    }
+4
source share
4 answers

You can use a class EqualityComparerlike this

if(EqualityComparer<T>.Default.Equals(value, default(T))
{
}

Stackoverflow: EqualityComparer <T> .Default vs. T.Equals

MSDN: EqualityComparer.Default

+5
source

One option you should make is to use an compareTointerface method IComparablewith a default of type ...

, , .

:

if (value.CompareTo(default(T)) == 0)

:

public static void WriteFlaggedValue<T>(this OutPacket outPacket, uint flag, T value, ref uint outputFlag) where T : struct,
      IComparable,
      IComparable<T>,
      IConvertible,
      IEquatable<T>,
      IFormattable
    {
        if (value.CompareTo(default(T)) == 0)
        {

        }

    }

null, .

+1

:

private T _minimumValue = default(T)

public bool IsEqualsZero(T value) 
{
    return (value.CompareTo(_minimumValue) == 0);
}

0

, Equals(T other), IEquatable<T>:

if (value.Equals(default(T)))
{
    // ...
}

default , OP , :

, , ( ):

The solution is to use the default keyword, which will return null for reference types and zero for numeric value types .


It should also be mentioned that just because you limit Thow structdoes not mean that you are guaranteed to Talways be numerical. For example, your method may accept DateTimeas a generic type. Perhaps you already know this and everything is in order.

Learn more about this here: What is a "base class" for C # numeric value types?

0
source

Source: https://habr.com/ru/post/1598078/


All Articles