有几个类,大部分属性基本一致,所以打算作一个基类,然后在这个基础上继承举个例子:TCustomItemSet = class(TPersistent)
public
  ......
  property Item[Index Integer]: TCustomItemSet read GetItem write SetItem;
end;然后TItemSet定义如下TItemSet = class(TCustomItemSet);在使用过程中想如下使用:function GetItemSet(Index: Integer): TItemSet;
begin
  with TItemSet.Create do
  begin
    Result := Item[Index];
  end;
end;这个时候报编译错误:类型不一致。因为基类的Item属性返回的是TCustomItemSet,但我使用中要求返回TItemSet类型,
请问我该怎么作呢?

解决方案 »

  1.   

    with TItemSet.Create do
    //……你这儿Create的TItemSet在什么地方释放?
      begin
        Result := Item[Index] as TItemSet;
      end;
      

  2.   

    To windindance(风舞轻扬):我的意思是希望TItemSet类的Item属性的类型就返回为TItemSet,而不是在外部作类型转换另外,这仅仅是一段不完善的演示代码,老大就不要追究释放的问题了吧?! :)
      

  3.   

    就是希望Item属性能返回本类的类型
      

  4.   

    TItemSet = class(TCustomItemSet);在TItemSet 中重新定义Item属性行不行?
    要做的事情也不是很多。
      

  5.   

    function GetItemSet(Index: Integer): TItemSet;
    begin
      Item[Index] := TItemSet.Create;
      Result := Item[Index];
    end;还得保证数组Item是TItemSet类型with TItemSet.Create do 根本就没有意义呀
      

  6.   

    不需要重新定义所有基类中的方法,
    只要定义Item这个属性和相关方法即可。
      

  7.   

    function GetItemSet(Index: Integer): TItemSet;
    begin
      with TItemSet.Create do
      begin
        Result := TItemSet(Item[Index]);
      end;
    end;
      

  8.   

    将function GetItemSet(Index: Integer): TItemSet;的返回类型改为TCustomItemSet。
    调用的时候进行强制转换。
    m:TItemSet;
    m:=GetItemSet(3) as TItemSet;
      

  9.   

    如果你坚持要实现你的目的,可以强制转化:
    Result := TItemSet(Item[Index]);但是VCL中一般是不采用这种方式的,而是返回一个通用的TCustomItemSet实例(TCustomItemSet的不同不同子类的Item属性返回不同的TCustomItemSet子类实例)。
    如果要强制转化,你就必须保证TCustomItemSet.GetItem 返回的的确是TItemSet或者其子类的实例;通常可以将TCustomItemSet.GetItem 虚化,在TItemSet覆盖处理。
    当然如果只是简单的:TItemSet = class(TCustomItemSet);
    TItemSet 相对于TCustomItemSet没有添加任何的成员,那么才可以简单的强制转化,但是此时TItemSet就没有任何意义了。————————————————————————————————————
    宠辱不惊,看庭前花开花落,去留无意;毁誉由人,望天上云卷云舒,聚散任风。
    ————————————————————————————————————
      

  10.   

    你给的代码好象不对
    TCustomItemSet = class(TPersistent)
    public
      ......
      property Item[Index Integer]: TCustomItemSet read GetItem write SetItem;
                                    --------------是这个吗, 不对吧
    end;然后TItemSet定义如下TItemSet = class(TCustomItemSet);在使用过程中想如下使用:function GetItemSet(Index: Integer): TItemSet;
    begin
      with TItemSet.Create do
      begin
        Result := Item[Index];
      end;
    end;
      

  11.   

    你是想TCustomItemSet及其派生累都有一个属性可以返回自身类型的对象而且想在TCustomItemSet就定义好这种接口,是吗?一般来讲,面向对象的程序设计中,接口的类型尽量抽象,才可以获得更大的便利你应该公布一个TCustomItemSet类型的接口,而在使用的时候去转换他楼上各位的说法都已经很清楚了,类型转换就能做到,再就是有其他的方法,也只会更复杂,除非你一定要追求形式,不然没必要这么做。
    使用一种语言,你必须遵守一些契约,这是难免的,你必须适应它,你想随心所欲,那是你熟悉它能做什么,不能做什么之后的事情。利用它能做的事情,绕过它不能做的,搭建出你想要得状态。