【问题标题】:Passing an interface to Codesite.Send in Delphi在 Delphi 中将接口传递给 Codesite.Send
【发布时间】:2014-03-15 08:00:29
【问题描述】:

我无法让 CodeSite.Send 使用声明为接口的变量。编译时错误是 E2250 没有可以使用这些参数调用的“发送”的重载版本。

如何在 CodeSite 中使用接口?

演示问题的代码示例:

type
  TForm1 = class(TForm)
    procedure FormCreate(Sender: TObject);
  end;

  IMyInterface = Interface(IInterface)['{9BCD2224-71F8-4CE7-B04C-30703809FAAD}']
    function GetMyValue : String;
    property MyVaue : String read GetMyValue;
  End;

  MyType = class(TInterfacedObject, IMyInterface)
    private
      sValue : string;
      function GetMyValue : String;
    published
      property MyVaue : String read GetMyValue;
  end;

var
  Form1: TForm1;
  test : IMyInterface;
  testType : MyType;

implementation

{$R *.dfm}

procedure TForm1.FormCreate(Sender: TObject);
begin
  test := MyType.Create;
  testType := MyType.Create;
  CodeSite.Send( 'testType', testType );  // This compiles
  CodeSite.Send( 'test', test );  // Compiler error here
  FreeAndNil(test);
end;

function MyType.GetMyValue : String;
begin
  Result := Self.sValue;
end;

【问题讨论】:

  • 如果它确实接受了一个接口,你希望它记录什么? MyValue? CodeSite 如何知道访问该特定属性? RTTI?据我所知,接口没有Send() 的重载,这就是您收到错误的原因。

标签: delphi codesite


【解决方案1】:

正如 Remy 在他的评论中指出的那样,当您指定接口时,CodeSite 不知道要记录什么。即使接收IInterface 的发送过载,它也不会有任何帮助,因为它仍然不知道您的特定接口IMyInterface

我知道的唯一解决方法是在您的实现类中实现 ICodeSiteCustomData 并使用类似

CodeSite.Send( 'test', test as ICodeSiteCustomData);

请注意,此功能在 CodeSite Express 中不可用。

【讨论】:

  • Remy 和 Uwe - 感谢您的回复!我希望它会像对类一样在接口上使用 RTTI。也许接口没有RTTI?这限制了 CodeSite 的实用性,因为我广泛使用接口。您的解决方法将是过多的代码维护。
【解决方案2】:

我找到了另一种可以解决问题的方法,但即使这样也有其缺点。

为实现接口发送重载的 TCodeSiteLogger 引入类帮助器。在内部,您将接口转换回实现实例并将其用于发送。请注意,这将为您提供基础对象的所有已发布属性,而不仅仅是接口的属性。

type
  TCodeSiteLoggerHelper = class helper for TCodeSiteLogger
    procedure Send(const Msg: string; const Value: IInterface); overload;
  end;

procedure TCodeSiteLoggerHelper.Send(const Msg: string;
  const Value: IInterface);
begin
  Send(Msg, Value as TObject);
end;

【讨论】:

  • 使用这种方法,您可以为特定的接口类型创建Send() 重载,而不必将它们转换回实现类(只能在 D2010+ 中完成,顺便说一句)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-29
  • 2012-08-29
  • 2017-11-23
  • 2010-10-11
  • 1970-01-01
相关资源
最近更新 更多