oxygene

How do you compare an oxygene class reference to classes?


Given the following code:

type
  Class1 = public class
  end;

  Class1Class = class of Class1;

  Class2 = public class (Class1)
  end;

  Class3 = public class (Class1)
  end;

  Class4 = public class
  public
    method DoSomething(c: Class1Class): Integer;
  end;

implementation

method Class4.DoSomething(c: Class1Class): Integer;
begin
  if c = Class2 then
    result := 0
  else if c = Class3 then
    result := 1
  else
    result := 2;
end;

How should DoSomething actually be written, as the equality comparisons throw the compiler error: Type mismatch, cannot find operator to evaluate "class of Class1" = "<type>"

Using is compiles, but in actuality the first conditional always evaluates to true no matter if Class2 or Class3 is passed in.

The goal is to write this in a cross-platform ways without using code specific to any one of the platforms Oxygene supports.


Solution

  • You must create class references for each class used in the conditionals and use the is operator.

    type
      Class1 = public class
      end;
    
      Class1Class = class of Class1;
    
      Class2 = public class (Class1)
      end;
    
      Class3 = public class (Class1)
      end;
    
      Class4 = public class
      public
        method DoSomething(c: Class1Class): Integer;
      end;
    
      Class2Class = class of Class2;
      Class3Class = class of Class3;
    
    implementation
    
    
    method Class4.DoSomething(c: Class1Class): Integer;
    begin
      if c is Class2Class then
        result := 0
      else if c is Class3Class then
        result := 1
      else
        result := 2;
    end;