A valid approach for generic operators

I have a class Gen<T>

and I want to be able to compare them. The following code cannot be compiled because the == parameter cannot be applied to the parent and child. Is there a way to make this comparison possible, or is this bad practice at all?

public class Parent{
    public int x;
}

public class Child:Parent{}

public class Gen<T> 
    where T : Parent 
{
    public T variable;
}

public static class Gen
{
    public static bool operator ==(Gen<Parent> left, Gen<Parent> right){
        if (left.variable.x == right.variable.x)
            return true;
        else
            return false;
    }
}

public void Test()
{
    Gen<Parent> foo = new Gen<Parent>();
    Gen<Child> bar = new Gen<Child>();

    if (foo == bar)
    {
        ...
    }
}

      

The full context is as follows:

  • Gen<T>

    equals ColorSet<T>

    where T: Color
  • Parent is equal to color
  • A child is a class that stores additional information for a color that is not needed for every Color object.

I want to access everyone Color

through a class ColorSet<T>

that looks like this:

public class ColorSet<T> where T : Color
{
     private T blue;
     private T red;
     private T green;

     public ColorSet()
     {
         Red = (T)Activator.CreateInstance(typeof(T), new object[] { });
         Red.Name = Values.Res.get("red");
         Blue = (T)Activator.CreateInstance(typeof(T), new object[] { });
         Blue.Name = Values.Res.get("blue");
         Green = (T)Activator.CreateInstance(typeof(T), new object[] { });
         Green.Name = Values.Res.get("green");
     }
}

      

But sometimes I need it ColorSet<Color>

, and sometimes ColorSet<Child>

for more information. And it should be possible to compare ColorSet<Color>

with ColorSet<Child>

, because they contain the most relevant information.

+3


source to share


3 answers


(expanding from comments). The generic class is apparently unnecessary. A valid approach to making operators work with generic types is to reuse the types so that they are not more generic.

ColorSet

can be defined as

public class ColorSet {
  private Color red;
  private Color green;
  private Color blue;

  protected ColorSet(Type type) {
    red = (Color)Activator.CreateType(type);
    red.Name = Values.Res.get("red");
    green = (Color)Activator.CreateType(type);
    green.Name = Values.Res.get("red");
    blue = (Color)Activator.CreateType(type);
    blue.Name = Values.Res.get("red");
  }

  public static ColorSet FromType<T>() where T : Color {
    return new ColorSet(typeof(T));
  }
}

      

Instead, new ColorSet<ExtendedColor>()

you now call ColorSet.FromType<ExtendedColor>()

.

This works as long as you don't really need to use it T

outside of your constructor.

If you, for example,

public T Red { get { return red; } }

      



you will need to change this to

public Color Red { get { return red; } }

      

properties.

However, if you have something like this and want to keep the generic type, you can put it in a derived generic class:

public class ColorSet<T> : ColorSet where T : Color {
  public ColorSet<T>() : base(typeof(T)) { }
  public new T Red { get { return (T)base.Red; } }
}

      

which still only needs operators for the base non-generic class ColorSet

.

+1


source


To go back to the original question / sample: it's not pretty, but it works (for your example - I only tested it with two) It uses reflection, although I'm not so happy about it:

public class Parent
{
    public int x;

    public Parent (int x)
    {
        this.x = x;
    }

    public override bool Equals(object o)
    {
        var p = o as Parent;
        if (object.Equals(p, null))
            return false;

        return this.x == p.x;
    }

    public override int GetHashCode()
    {
        return x;
    }

    public static bool operator ==(Parent a, Parent b)
    {
        return a.Equals (b);
    }

    public static bool operator !=(Parent a, Parent b)
    {
        return !(a == b);
    }

}

public class Child : Parent
{
    public Child (int x)
        : base(x)
    {

    }
}

public class Gen<T> 
    where T : Parent 
{
    public T variable;

    public Gen (T x)
    {
        this.variable = x;
    }

    public override bool Equals(object o)
    {
        if (object.Equal(o, null)) return false;

        // CAUTION: VERY DIRTY - just a quick reply to hvd - should check/remove this with test cases!
        try
        {
           var oT = o.GetType ().GetGenericTypeDefinition ();
           var tT = this.GetType ().GetGenericTypeDefinition ();
           if (tT != oT)
               return false;

           // for example this:
           // var oVar = o.GetType().GetField ("variable").GetValue (o);
           // should really be
           var varField = o.GetType().GetField("variable");
           if (varField == null) return;
           var oVar = varField.GetValue(o);

           if (object.Equals(oVar, null)) 
              return object.Equals(this.variable, null);

           return this.variable.Equals (oVar);
         } catch { return false; }
    }

    public override int GetHashCode()
    {
        return variable.GetHashCode();
    }

    public static bool operator ==(Gen<T> a, object b)
    {
        return a.Equals (b);
    }

    public static bool operator !=(Gen<T> a, object b)
    {
        return !(a == b);
    }

}

      

Here's yours and another example:



public static void Test()
{
    Gen<Parent> foo = new Gen<Parent>(new Parent(5));
    Gen<Child> bar = new Gen<Child>(new Child(5));
    Gen<Child> bas = new Gen<Child>(new Child(6));

    if (foo == bar)
        Console.WriteLine ("equal");
    else
        Console.WriteLine ("not-equal");

    if (foo == bas)
        Console.WriteLine ("equal");
    else
        Console.WriteLine ("not-equal");
}

      

btw: you don't really need (==) and (! =) in the class Parent

, but it doesn't hurt

+1


source


public class IGen<out T> 
    where T : Parent 
{
    T Variable{ get; }
}

public class Gen<T>
    : IGen<T>
    where T : Parent 
{
    public T Variable {get;set;}

    private static Func<T, T, bool> _equal;

    static Gen()
    {
        var left = Expression.Parameter(typeof(T));
        var right = Expression.Parameter(typeof(T));
        var body = Expression.Equal(left, right);
        var lambda = Expression.Lambda<Func<T, T, bool>>(body, left, right);
        _equal = lambda.Compile();
    }

    public static bool operator ==(Gen<T> left, Gen<T> right)
    {
        return _equal(left.Variable, right.Variable);
    }


    public static bool operator ==(Gen<T> left, IGen<T> right)
    {
        return _equal(left.Variable, right.Variable);
    }


    public static bool operator ==(IGen<T> left, Gen<T> right)
    {
        return _equal(left.Variable, right.Variable);
    }
}

      

0


source







All Articles