2016-06-03 2 views
1

두 개의 인터페이스, ISomeInterfaceRO (읽기 전용) 및 ISomeInterface가 있습니다.Delphi - 다른 인터페이스로 인터페이스

ISomeInterfaceRO = interface(IInterface) ['{B28A9FB0-841F-423D-89AF-E092FE04433F}'] 
function GetTest: Integer; 
    property Test : integer read GetTest; 
end; 

ISomeInterface = interface(ISomeInterfaceRO) ['{C7148E40-568B-4496-B923-89BB891A7310}'] 
    procedure SetTest(const aValue: Integer); 
    property Test : integer read GetTest write SetTest; 
end; 

TSomeClass = class(TInterfacedObject, ISomeInterfaceRO, ISomeInterface) 
private 
    fTest: integer; 
protected 
    function GetTest: integer; 
    procedure SetTest(const aValue: integer); 
public 
    property Test: integer read GetTest write SetTest; 
end; 

function TSomeClass.GetTest: integer; 
begin 
    Result := fTest; 
end; 

procedure TSomeClass.SetTest(const aValue: integer); 
begin 
    fTest := aValue; 
end; 

그 후, 나는 ISomeInterface로 TSomeClass 인스턴스를 생성하고 그것을 채울 경우에만, 한 곳을 제외하고 인터페이스를 읽어 사용합니다. 예 :

Function GetSome: ISomeInterfaceRO; 
var 
    SomeInterface: ISomeInterface; 
begin 
    SomeInterface := TSomeClass.Create; 
    SomeInterface.Test := 10; 
    result := SomeInterface as ISomeInterfaceRO; 
end; 

제 질문은 "결과 : = SomeInterface as ISomeInterfaceRO;"입니다. 안전하고 권장되는 건설입니까? 아니면이 작업을 수행하는 또 다른 방법입니까? 해당 코드를 디버깅하고 컴파일러가 참조 횟수를 ISomeInterface로 적절하게 줄였으며 "as"를 사용하면 ISomeInterfaceRO가 증가했습니다.

+2

그것은이 대답 한 후 질문을 변경 옳지 않아 : 그것은 당신이 당신이 직접 쓸 수 있도록 내가 그러나 값을 가져 TSomeClass에 생성자를 둘 것

Result := SomeInterface; 

을 쓸 수 있다는 것을 의미합니다. 약을 복용하고 실수를 인식해야합니다. 결국 G +에서 발생한 문제에 대해 공정한 경고를주었습니다. 이제 새로운 질문을해야합니다. –

+1

좋아요, 나는 장래를 위해 그것을 기억할 것입니다 – Stregor

답변

4
Result := SomeInterface as ISomeInterfaceRO; 

전혀 따라서 ISomeInterfaceISomeInterfaceRO에서 상속하기 때문에 SomeInterfaceResult 호환 할당이 필요한 안전하지만,하지 않습니다.

Result := TSomeClass.Create(10); 
+0

안녕 스테판! 의견을 보내 주셔서 감사합니다. 나도 알다시피, 내 이전 예제 코드는 내 진짜 질문에 초점을 맞추고 있지 않습니다 :) 그래서, 그것을 편집하고 상속을 제거합니다. – Stregor

관련 문제