Class restriction

Trying to define a class restriction, but get an error:

public class Utilities3<T> where T : IComparable
{
    public T Max<T>(T a, T b) 
    {
        return a.CompareTo(b) > 0 ? a : b;
    }
}

'T' does not contain a definition for "CompareTo", and the extension method "CompareTo" cannot be found that takes the first argument of type "T" (do you miss the using directive or assembly references?)

Unable to resolve CompareTo character

error

Function restriction works fine:

public class Utilities2<T>
{
    public T Max<T>(T a, T b) where T : IComparable
    {
        return a.CompareTo(b) > 0 ? a : b;
    }
}

Why doesn't class restriction work?

+4
source share
3 answers

This line of code:

public T Max<T>(T a, T b) 

Defines a new <T> that overwrites the one you use for the class. Remove it & lt; T> in the method, and instead you will use a class constraint

+5
source

, T T, . , , , , .

public class Utilities3<T> where T : IComparable
{
    public T Max(T a, T b) 
    {
        return a.CompareTo(b) > 0 ? a : b;
    }
}

. - , , , .

+7

, . :

public class Utilities
{
    public T Max<T>(T a, T b) where T : IComparable
    {
        return a.CompareTo(b)>0 ? a : b;
    }
    public bool Equals<T>(T a, T b) where T : IEquatable<T>
    {
        return a!=null ? a.Equals(b) : b==null;
    }
}

, class Utilties where T : IComparable, IEquatable<T>, ...

+1

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


All Articles