Pergunta

am trying to do this in delphi but am not sure about the CTYPE function.

Dim docStyleSheet As mshtml.IHTMLStyleSheet = CType(doc.styleSheets.item(0), mshtml.IHTMLStyleSheet)
Dim docStyleRules As mshtml.HTMLStyleSheetRulesCollection = CType(docStyleSheet.rules, mshtml.HTMLStyleSheetRulesCollection)

why we cant simply do this in delphi:

stylesheet :=  document.styleSheets.item(0) As IHTMLStyleSheet;

the full code can be found at this link https://stackoverflow.com/a/2996819

Tlama, David... thanx for the correction yes its a vb code.

Foi útil?

Solução

AS. the answer was extended few times, as more and more info was uncovered turning the question from "what is CType function?" to "How to convert OleVariant to a required Interface type?". Thus the answer gradually covers all those topics.

So, you met unknown function in Microsoft Visual Basic code. What is one to do, when he meets something yet unknown? Go Google.

Google.com with text CType MSDN gives us this link in its top results: http://msdn.microsoft.com/en-us/library/vstudio/4x2877xb.aspx

Returns the result of explicitly converting an expression to a specified data type, object, structure, class, or interface. If no conversion is defined from expression to typename (for example, from Integer to Date), Visual Basic displays a compile-time error message.

So we have to reproduce typecast in Delphi, preferably compile-type type-cast, if possible.

Google.com with text typecast docwiki gives us this link in its top results:

Which in turn gives us one more link referenced in the text:

So you have two syntaxes to try. One you tried and ruled out - the one with AS operator. Then try another, direct typecast syntax.

stylesheet :=  IHTMLStyleSheet( document.styleSheets.item(0) );

Sometimes if above fails it also helps doing double typecast, Variant -> IUnknown -> certain interface, but in many cases that is but redundant version of the upper code.

stylesheet :=  IHTMLStyleSheet( IInterface( document.styleSheets.item(0) ) );

Well, now that it was told that the source expression datatype is OleVariant we can read documentation with more precise aim, about Variant datatype conversions (OleVariant is little different from Variant in modern Delphi):

  • AS operator is applicable to classes, objects and interfaces. It is not applicable to Variant expressions. This answers the original "why we cannot..." question.
  • Documentation on Variant type suggests converting it using direct typecast syntax.

.

stylesheet :=  IInterface( document.styleSheets.item(0) ) as IHTMLStyleSheet;

If wished, you can even use (over?)defensive programming using http://docwiki.embarcadero.com/Libraries/XE2/en/System.Variants.VarType to check that you got varUnknown or varDispatch before attempting at getting IUnknown out of the returned value.

PS. The question seems as a duplicate now.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top