Ver Mensaje Individual
  #1  
Antiguo 30-05-2007
Avatar de Neftali [Germán.Estévez]
Neftali [Germán.Estévez] Neftali [Germán.Estévez] is offline
[becario]
 
Registrado: jul 2004
Ubicación: Barcelona - España
Posts: 18.267
Reputación: 10
Neftali [Germán.Estévez] Es un diamante en brutoNeftali [Germán.Estévez] Es un diamante en brutoNeftali [Germán.Estévez] Es un diamante en bruto
Acceder al objeto asociado a una prop. (RTTI)

Esta función permite acceder al objeto (componente) asociado a una propiedad published de un componente vía RTTI.
Al utilizar RTTI es necesario añadir la unit TypInfo al uses.

Código Delphi [-]
// Devuelve el objeto asociado a una propiedad (RTTI).
function GetPropAsObject(AObj: TObject; const PropName:String):TObject;
const
  EBLOCK = 'GetPropAsString';
var
  PInfo: PPropInfo;
  LObject: TObject;
Begin

  Result := nil;

  // Existe la propiedad
  if not ExistProp(AObj, PropName) then begin
    Exit;
  end;

  // Intentamos acceder (con un puntero) a la info. de la propiedad
  PInfo := GetPropInfo(AObj.ClassInfo, PropName);

  // Se ha encontrado la propiedad con éste nombre; Chequear el tipo...
  if (PInfo^.PropType^.Kind = tkClass) then begin

    LObject := GetObjectProp(AObj, PInfo);
    // Nada...
    if (LObject <> nil) then begin
      Result := LObject;
    end;
  end
  else begin
    Result := nil;
  end;
end;

NOTA: Usa la función ExistProp del truco 405.

Un ejemplo de utilización se muestra a continuación; Aquí se busca en todos los componentes del formulario los que tienen la propiedad DataSource; Para los que la tienen asignada se muestra el nombre del DataSourde asignado.

Código Delphi [-]
  // recorrer todoslos controles del form...
  for I := 0 to (Self.ComponentCount - 1) do begin
    comp := Self.Components[i];

    obj := GetPropAsObject(comp, 'DataSource');

    Memo1.Lines.Add('Componente: ' + comp.Name);
    if not Assigned(Obj) then begin
      Memo1.Lines.Add('  -> no Asignado');
    end
    else begin
      // Es un DataSource?
      if (obj is TDataSource) then begin
        Memo1.Lines.Add('  DataSource: ' + TDataSource(obj).Name);
      end
      else begin
        Memo1.Lines.Add('  -> Asignación incorrecta');
      end;
    end;

  end;
Responder Con Cita