Types Incompatibles

Delphi

20/07/2011

Tenho esse erro: [Error] clsListValidator.pas(106): Incompatible types: 'TDocumentoNovo' and 'IDocument' Essa é a procedure
procedure TListValidator.Validate(Documento: IDocument);
var
  IntNum: integer;
begin
  for intNum := 0 to Self.Count - 1 do
  begin
    try
      Self[intNum].Validate(Documento);
    except
      On E:EPluginException do
        Raise EPluginException.Create(E.ErrorCode, E.Message);
      On E:Exception do
        Raise Exception.Create(E.Message);
    end; // Try..Except
  end; // For
  
end;
  Porem temos uma Interface onde está sendo declara assim: procedure Validate(Documento: TDocumentoNovo');overload; Ela é overload, e segundo a regra de OOP, uma função Overload, pode quantidade de parâmetros diferentes ou tipos diferentes ou retorno(se for função) Então, porque continua dando esse erro.
Pjava

Pjava

Curtidas 0

Respostas

Marco Salles

Marco Salles

20/07/2011

Como esta a definicao dessas procedures .. Nao disse implementacao , disse Definicao..
GOSTEI 0
Pjava

Pjava

20/07/2011

O que eu acho interessante, é que a IDocument do parâmetro da procedure Validator, se eu clico nele(Ctrl+Mouse), ele abre a unit IDocumentUnit, porem essa Unit parece não estar no meu projeto, pois eu puxo as units associadas ao projeto(Ctrl+F12) não aparece na lista das units do projeto. Isso eu tenho percebido que todas as Units de Interface não aparece. Acho que elas são de algum componente(Temos um aqui chamado Interface). Esse projeto não fui eu quem fiz, hoje é meu 10º dia na empresa e agora que to pegando ele(Aliás desde segunda e parei ontem e retomei hj). Se for parte de um componente, pode da esse pau?
GOSTEI 0
Marco Salles

Marco Salles

20/07/2011

O que eu acho interessante, é que a IDocument do parâmetro da procedure Validator, se eu clico nele(Ctrl+Mouse), ele abre a unit IDocumentUnit, porem essa Unit parece não estar no meu projeto, pois eu puxo as units associadas ao projeto(Ctrl+F12) não aparece na lista das units do projeto. Isso eu tenho percebido que todas as Units de Interface não aparece. Acho que elas são de algum componente(Temos um aqui chamado Interface). Esse projeto não fui eu quem fiz, hoje é meu 10º dia na empresa e agora que to pegando ele(Aliás desde segunda e parei ontem e retomei hj). Se for parte de um componente, pode da esse pau?


Entao , quando vc clica por exemplo em Tbutton abre a Unidade StdCtrls .. se vc for olhar na lista das Unidades que fazem parte do seu projeto essas Unidade n'ao esta , por[em ela provavelmente esta declarada na uses ou da seccao Interface ou da seccao Implementation .

Pode ser tambem que nen abra o .pas , ha caso em que so a dcu e liberada ( quando o autor quer preservar o codigo fonte ) , por exemplo a Variavel gsAppPath esta declarada em (SWSystem no delphi 2007 a 2010 e IWSystem no DelphiXe) . Porem nao foi liberado o .pas desta Unidade
GOSTEI 0
Pjava

Pjava

20/07/2011

Salles, esse projeto tá uma bagunça e o motivo de estarmos aqui, além de dar manutenção e criar novas coisas é também organizar a bagunça. O que você me aconselha a fazer? Falei do Salles, mas qualquer outro colega pode dar sua contribuição.
GOSTEI 0
Pjava

Pjava

20/07/2011

Abaixo a interface IDocument e a Unit onde me dá o erro Pessoal, não sei se este é o problema, mas veja isso. Eu tô perdido nisso. Tenho uma Unit onde está a declaração da Validate, mas passando o TDocumentoNovo e não o IDocument. Nessa Unit tem um ponteiro  de método assim: TNotifyValidate   = procedure (Documento: TDocumentoNovo) of object; Esse ponteiro(TNotifyValidate) está na Unit onde o erro está acontecendo, com várias eventos dele, Onbefore, OnAfter e etc... Mesmo se eu comento essa declaração da procedure Validate e crio outra passando parametros do tipo IDocument, ele continua buscando o tipo TDocumentoNovo e essa declaração, só existe nessa Interface(IValidator). Abaixo as Units envolvidas:   A Unit com a Interface IValidator
interface
uses
  SysUtils, Windows, Messages, Classes, Graphics, Controls, Forms, Dialogs,
  clsDocumento, IPluginUnit;
type
  TOnErrorValidate  = procedure (FieldName: String) of object;
  TNotifyValidate   = procedure (Documento: TDocumentoNovo) of object;

  IValidator = interface(IPlugin)
    ['{A9688CA1-4117-42D7-A790-60B950B2D264}']
    function GetOnAfterValidate:   TNotifyValidate;
    function GetOnBeforeValidate: TNotifyValidate;
    function GetOnErrorValidate: TOnErrorValidate;
    procedure SetOnBeforeValidate(const Value: TNotifyValidate);
    procedure SetOnAfterValidate(const Value: TNotifyValidate);
    procedure SetOnErrorValidate(const Value: TOnErrorValidate);
    procedure Validate(Documento: TDocumentoNovo);{overload;
    procedure Validate(Documento: IDocument);overload;//Criado por Paulo }
    property OnAfterValidate: TNotifyValidate read GetOnAfterValidate write
        SetOnBeforeValidate;
    property OnBeforeValidate: TNotifyValidate read GetOnBeforeValidate write
        SetOnBeforeValidate;
    property OnErrorValidate: TOnErrorValidate read GetOnErrorValidate write
        SetOnErrorValidate;
  end;
  IteratorValidator = interface
    ['{33D0C0ED-91A4-468E-AF5B-A7E5B5C5DAC7}']
    procedure First();
    procedure Next();
    function IsDone(): Boolean;
    function CurrentItem: IValidator;
  end;
  IListValidator = interface
    ['{8F2F5645-3BC1-427D-89AC-A39C370AD957}']
    function  CreateIterator(): IteratorValidator;
    procedure Add(Validator: IValidator);
    procedure Delete(Index: Integer);
    function  Item(Index: integer): IValidator;
    function  Count(): integer;
  end;
implementation
end.
  A Unit onde está a interface TDocumentoNovo  
type
  TDocumentoNovo = class(TClassBase, IDocument)
  private
    FCod_Caixa: Integer;
    FCodDocumento: Integer;
    FCod_Etiqueta: Integer;
    FCod_Usuario: Integer;
    FComplemento: String;
    FDataFinal: TDate;
    FDataInicial: TDate;
    FData_Digitacao: TDate;
    FDescricao: String;
    FPrevisaoExpurgo: TDate;
    FSequencialFinal: Integer;
    FSequencialInicial: Integer;
    FDestroyTipoDocumento: Boolean;
    FTipoDocumento: TTipoDocumento;
    FDestroyCaixa: Boolean;
    FCaixa: TCaixa;
    FCodTipoDocumento: Integer;
    FHasAutoComplete: Boolean;
    FAuditoria_Interna: String;
    FAnomalias: TListBase;
    FListValor: TListBase;
    FStatus: String;
    FCod_Status: Integer;
    FCod_xSolicitante: Integer;
    FCarga: TCarga;
    //Preferimos usar o Cod_Auditoria ao inves da Classe FAuditoria por quetão de tempo devido a urgencia de entrega
    // que se se faz presente nesta data
    //FAuditoria:TAuditoria;
    //FDestroyAuditoria: Boolean;
    FCod_Auditoria : integer;
    FHashRegistro: String;
    function GetCliente(): TCliente;
    function GetLocal(): TLocal;
    function GetDepartamento(): TDepartamento;
    function GetComplemento: String;
    function GetDataFinal: TDate;
    function GetDataInicial: TDate;
    function GetDescricao: String;
    function GetSequencialFinal: Integer;
    function GetSequencialInicial: Integer;
    function getQuantidadeDigitacao: Integer;
    procedure SetCod_Caixa(Value: Integer);
    procedure SetCod_Documento(Value: Integer);
    procedure SetCod_Usuario(Value: Integer);
    procedure SetComplemento(const Value: String);
    procedure SetDataFinal(Value: TDate);
    procedure SetDataInicial(Value: TDate);
    procedure SetData_Digitacao(Value: TDate);
    procedure SetDescricao(const Value: String);
    procedure SetPrevisaoExpurgo(Value: TDate);
    procedure SetSequencialFinal(Value: Integer);
    procedure SetSequencialInicial(Value: Integer);
    //procedure SetCodTipoDocumento(Value: Integer);
    function GetCodTipoDocumento: Integer;
    function GetCodDocumento: Integer;
    procedure SetCodDocumento(Value: Integer);
    function  GetHasAutoComplete: Boolean;
    procedure SetHasAutoComplete(Value: Boolean);
    procedure SetCaixa(const Value: TCaixa);
    function GetCaixa: TCaixa;
    procedure SetAuditoria_Interna(const Value: String);
    function GetAnomalias: TListBase;
    procedure SetAnomalias(Value: TListBase);
    function GetStatus: String;
    procedure SetStatus(const Value: String);
    function getValorIndices(): TListBase;
    function getTipoDocumento: TTipoDocumento;
    procedure setTipoDocumento(const value: TTipoDocumento);
    procedure SetCod_Status(const Value: Integer);
    function GetCod_Status: Integer;
    function GetAuditoria_Interna: String;
    function GetCod_Caixa: Integer;
    function GetCod_Etiqueta: Integer;
    function GetCod_Usuario: Integer;
    function GetData_Digitacao: TDate;
    procedure SetCod_Etiqueta(const Value: Integer);
    function GetCod_xSolicitante: Integer;
    procedure SetCod_xSolicitante(Value: Integer);
    function GetPrevisaoExpurgo: TDate;
    function GetCarga: TCarga;
    //function GetAuditoria: TAuditoria;
    //procedure SetAuditoria(const Value: TAuditoria);
    function GetCod_Auditoria: integer;
    procedure SetCod_Auditoria(const Value: integer);
    function getHashRegistro: String;
    procedure setHashRegistro(const Value: String);
    function QuantidadeDigitacaoCustomizavel: Integer;
  public
    constructor Create; override;
    destructor Destroy; override;
    procedure PopularValorIndice();
    //Colocados aqui para nao serem lidas em tempo de execucao usando o metodo AssignPropertys
    //pois causa Access Violation.
    property Carga: TCarga read GetCarga;
    property Cliente: TCliente read GetCliente;
    property Local:   TLocal read GetLocal;
    property Departamento: TDepartamento read GetDepartamento;
    property QuantidadeDigitacao: Integer read GetQuantidadeDigitacao;
    property CodTipoDocumento: Integer read GetCodTipoDocumento;
  published
    property TipoDocumento: TTipoDocumento read GetTipoDocumento write SetTipoDocumento;
    property Caixa: TCaixa read GetCaixa write SetCaixa;
    property Cod_Caixa: Integer read GetCod_Caixa write SetCod_Caixa;
    property CodDocumento: Integer read GetCodDocumento write SetCod_Documento;
    property Cod_Etiqueta: Integer read GetCod_Etiqueta write SetCod_Etiqueta;
    property Cod_Usuario: Integer read GetCod_Usuario write SetCod_Usuario;
    property Complemento: String read GetComplemento write SetComplemento;
    property DataFinal: TDate read GetDataFinal write SetDataFinal;
    property DataInicial: TDate read GetDataInicial write SetDataInicial;
    property Data_Digitacao: TDate read GetData_Digitacao write SetData_Digitacao;
    property Descricao: String read GetDescricao write SetDescricao;
    property PrevisaoExpurgo: TDate read GetPrevisaoExpurgo write
        SetPrevisaoExpurgo;
    property SequencialFinal: Integer read GetSequencialFinal write
        SetSequencialFinal;
    property SequencialInicial: Integer read GetSequencialInicial write
        SetSequencialInicial;
    property HasAutoComplete: Boolean read GetHasAutoComplete write SetHasAutoComplete;
    property Auditoria_Interna: String read GetAuditoria_Interna write SetAuditoria_Interna;
    property Anomalias: TListBase read GetAnomalias write SetAnomalias;
    property Status: String read GetStatus write SetStatus;
    property ValorIndices: TListBase read GetValorIndices;
    property Cod_Status: Integer read GetCod_Status write SetCod_Status;
    property Cod_xSolicitante: Integer read GetCod_xSolicitante write SetCod_xSolicitante;
    //Preferimos usar o Cod_Auditoria ao inves da Classe FAuditoria por quetão de tempo devido a urgencia de entrega
    // que se se faz presente nesta data
    property Cod_Auditoria : integer read GetCod_Auditoria write SetCod_Auditoria;
    property HashRegistro: String read getHashRegistro write setHashRegistro;
  end;
  A Unit onde aparece o erro  
Type
  TListValidator = class(TObject)
  private
    FListValidator: TListPlugins;
    FOnAfterValidate: TNotifyValidate;
    FOnBeforeValidate: TNotifyValidate;
    FOnErrorValidate: TOnErrorValidate;
    function GetItems(Index: integer): IValidator;
    procedure SetItems(Index: integer; const Value: IValidator);
    procedure SetOnBeforeValidate(EventHandle: TNotifyValidate);
    procedure SetonAfterValidate(EventHandle: TNotifyValidate);
    procedure SetOnErrorValidate(EventHandle: TOnErrorValidate);
  public
    constructor Create;
    destructor Destroy; override;
    function Add(Validator: IValidator): Integer;
    function Count: Integer;
    procedure Delete(Index: integer); overload;
    procedure Delete(GUID: string); overload;
    procedure Clear;
    procedure Validate(Documento: IDocument);
    property Items[Index: integer]: IValidator read GetItems write SetItems;
        default;
    property OnErrorValidate: TOnErrorValidate read FOnErrorValidate write SetOnErrorValidate;
    property OnBeforeValidate: TNotifyValidate read FOnBeforeValidate write SetOnBeforeValidate;
    property OnAfterValidate:  TNotifyValidate read FOnAfterValidate write SetOnAfterValidate;
  end;
implementation
uses
  SysUtils, Exceptions;
{ TListValidator }
{
******************************** TListValidator ********************************
}
constructor TListValidator.Create;
begin
  FListValidator := TListPlugins.Create;
end;
destructor TListValidator.Destroy;
begin
  FreeAndNil(FListValidator);
  inherited;
end;
function TListValidator.Add(Validator: IValidator): Integer;
begin
  Result := FListValidator.Add(Validator);
  // Se houverem eventos de validações associados, associa a cada elemento inserido
  if Assigned(Self.OnBeforeValidate) then
    Validator.OnBeforeValidate := Self.OnBeforeValidate;
  if Assigned(Self.OnAfterValidate) then
    Validator.OnAfterValidate  := Self.OnAfterValidate;
  if Assigned(Self.OnErrorValidate) then
    Validator.OnErrorValidate  := Self.OnErrorValidate;
end;
function TListValidator.Count: Integer;
begin
  Result := FListValidator.Count();
end;
procedure TListValidator.Delete(Index: integer);
begin
  FListValidator.Delete(Index);
end;
procedure TListValidator.Delete(GUID: string);
begin
  FListValidator.Delete(GUID);
end;
function TListValidator.GetItems(Index: integer): IValidator;
begin
  Result := IValidator(FListValidator[Index]);
end;
procedure TListValidator.SetItems(Index: integer; const Value: IValidator);
begin
  FListValidator[Index] := Value;
end;
procedure TListValidator.Validate(Documento: IDocument);
var
  IntNum: integer;
begin
  for intNum := 0 to Self.Count - 1 do
  begin
    try
      Self[intNum].Validate(Documento);//Aqui dá o erro
    except
      On E:EPluginException do
        Raise EPluginException.Create(E.ErrorCode, E.Message);
      On E:Exception do
        Raise Exception.Create(E.Message);
    end; // Try..Except
  end; // For
  
end;
procedure TListValidator.Clear;
begin
  FListValidator.Clear;
end;
procedure TListValidator.SetOnAfterValidate(EventHandle: TNotifyValidate);
var
  intNum: integer;
begin
  FOnAfterValidate := EventHandle;
  for intNum := 0 to Self.FListValidator.Count - 1 do
    IValidator(Self.FListValidator[intNum]).OnAfterValidate := FOnAfterValidate;  
end;
procedure TListValidator.SetOnBeforeValidate(
  EventHandle: TNotifyValidate);
var
  IntNum: integer;
begin
  FOnBeforeValidate := EventHandle;
  // Seta o evento de validação para todos os elementos da lista
  for intNum := 0 to Self.FListValidator.Count - 1 do
    IValidator(Self.FListValidator[intNum]).OnBeforeValidate := EventHandle;
  
end;
procedure TListValidator.SetOnErrorValidate(EventHandle: TOnErrorValidate);
var
  intNum: integer;
begin
  FOnErrorValidate := EventHandle;
  for intNum := 0 to Self.FListValidator.Count - 1 do
    IValidator(Self.FListValidator[intNum]).OnErrorValidate := FOnErrorValidate;
end;
GOSTEI 0
Vitor Rubio

Vitor Rubio

20/07/2011

PJava, veja bem, você usa Self[intNum].Validate(Documento) certo? Essa propriedade deve trazer um IValidator para você chamar o método validate passando um idocument, certo?
Na sua interface IValidator e em todas as classes que a implementam use apenas procedure Validate(Documento: IDocument)
O "typecast" de uma classe que implementa uma interface para a interface em si sempre é automático e implícito. O contrário deve ser explícito. 
Evite usar tipos concretos em parâmetros de métodos e propriedades, pois isso cria uma dependência/acoplamento desnecessário com as implementações das interfaces em si. Use sempre os "tipos interface" nos argumentos. 
Outra coisa: a classe TListValidator não teria que implementar IListValidator?
tente dar um showmessage no nome da classe do objeto, só para ver que objeto que está chegando antes de dar o validate. 
A sua interface IDocument tem guid?
GOSTEI 0
Pjava

Pjava

20/07/2011

Olá Vitor, vou fazer isso sim. Esse projeto não fui eu quem fiz, pois eu estou apenas 10 dias aqui nessa empresa e peguei esse projeto para dar continuidade. Tenho algumas limitações nesse sentido. Vou testar sim e dependendo do resultado eu posto aqui novamente.
GOSTEI 0
Pjava

Pjava

20/07/2011

Respondi o post e agora que percebi. Não é possível dar um ShowMessage, porque não compila o projeto. Ele para aí, onde marquei o erro. Se eu implemento a Interface IListValidator na classe TListValidator, me dá outros erros como: [Error] clsListValidator.pas(36): Undeclared identifier: 'CreateIterator' Esse 'CreateIterator' está dentro da Interface IListValidator.
GOSTEI 0
POSTAR