I wrote this code in Delphi XE which assign the GUID of the interface from GUID const. the code compile ok, but I want to know if this a valid declaration?
const
IID_IFoo: TGUID = '{00000000-6666-6666-6666-666666666666}';
type
开发者_StackOverflow IFoo = interface(IDispatch)
[IID_IFoo]
//properties
//methods
end;
You can do this, but the question is why would you want to ?
If you wish to refer to the GUID of an interface rather than the name of the interface, then as long as that interface has an associated IID (GUID) then you can use the interface name where a TGUID is expected:
type
IFoo = interface(IDispatch)
['{00000000-6666-6666-6666-666666666666}']
//properties
//methods
end;
// meanwhile, elsewhere in the project...
sFooIID := GUIDToString(IFoo);
This is a less "noisy" declaration of the interface and avoids the possibility that you might declare/reference an IID constant which isn't actually associated with the interface you think it is (or which hasn't been associated with that IID at all).
const
IID_Foo = '{00000000-6666-6666-6666-666666666666}';
IID_Bar = '{00000000-6666-6666-6666-777777777777}';
type
IFoo = interface(IDispatch)
[IID_Bar] // WHOOPS!
:
end;
IBar = interface(IDispatch)
// WHOOPS again!!
:
end;
// Meanwhile, elsewhere in the project
sBarID := GUIDToString(IID_Bar); // Works, but is the IID of IFoo, not IBar
sFooID := GUIDToString(IID_Foo); // Works, but is an IID not associated with any interface
Using the interface itself as both interface and IID, rather than having a separate const declaration, removes the potential for these mistakes.
When using separate constant declarations for IID's - if you absolutely have to - you can protected against one of these problems by never-the-less using interfaces where IID's are expected. But this arguably makes things worse in the case where the wrong IID has been used for a particular interface:
// Cannot make the mistake of using an interface as a GUID if it has no IID at all
sBarID := GUIDToString(IBar); // Does not compile - IBar has no IID
// But if it's the wrong IID then you get results that are "correct" but not expected:
a := GUIDToString(IFoo);
b := GUIDToString(IID_Foo);
a <> b
Yes, this is perfect fine. If you wanna know why you should use guids in interfaces, check This out.
EDIT
You can make sure it works. Just use QueryInterface using the guid and you will see it worls
精彩评论