简体   繁体   中英

Valid approach for generic operators

I have a class Gen<T> and I want to make it possible to compare them. The following code cannot be compiled, because the == cannot be applied to Parent and Child. Is there a way to make this comparison possible, or is this bad practice in general?

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 the following:

  1. Gen<T> equals ColorSet<T> where T:Color
  2. Parent equals Color
  3. Child is a class that stores additional information for a color, which are not necessary for every Color objects.

I want to access every Color through the ColorSet<T> class, which 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 ColorSet<Color> and sometimes ColorSet<Child> for the additional information. And it should be possible to compare ColorSet<Color> with ColorSet<Child> because they have the most relevant information in common.

To come back to your original question/sample: this is not beautifull but it works (for your example - i only tested it with two) It uses reflection though so I'm not that happy with 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 is 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 the (==) and (!=) on the Parent class - but well it does not hurt

(expanding from the comments) A generic class doesn't seem to be necessary. A valid approach for getting operators to work for generic types is to re-work the types so that they're no longer generic.

ColorSet could 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 of new ColorSet<ExtendedColor>() , you would now call ColorSet.FromType<ExtendedColor>() .

This works so long as you don't actually need to use your T outside of your constructor.

If you had, for instance, a

public T Red { get { return red; } }

property, you would need to change that to a

public Color Red { get { return red; } }

property.

However, if you have anything like that, and you do want to keep the generic type, you can then put that 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 ColorSet class.

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM