Jump to content
Sonjli

Strange behavior with "is" operator

Recommended Posts

Hello.

I am using RTTI to loop trough attributes.

If I do this I get FALSE with the IS operator. I premise that "Attribute" is surely and absolutely "MyAttributeOne" class.

          if Attribute Is MyAttributeOne then
            IsMyAttributeOne := True

But if I do this

          if Attribute.ClassNameIs('MyAttributeOne') then
            IsMyAttributeOne := True

Then I get a wonderful TRUE.

Any idea about this?

 

Thanks

Eddy

Share this post


Link to post

Cannot reproduce:

 

unit Unit1;

interface type
	MyAttributeOne = class(TCustomAttribute);

	[MyAttributeOne]
	TMyObject = class(TObject);

implementation

end.
program Project1;

uses
	System.SysUtils,
	System.Rtti,
	Unit1 in 'Unit1.pas';
var
	ctx: TRttiContext;
	rttiType: TRttiType;
	attribute: TCustomAttribute;
begin
	ctx := TRttiContext.Create();
	rttiType := ctx.GetType( TypeInfo(TMyObject) );

	for attribute in rttiType.GetAttributes() do
		if(attribute is MyAttributeOne) then
			WriteLn('It is MyAttributeOne!')
		else
			WriteLn('It is something else');

end.

will output

It is MyAttributeOne!

Share this post


Link to post

Do you perhaps have code in different modules? Like code in an exe and a dll and the object is passed between the modules?

Share this post


Link to post
5 hours ago, Sonjli said:

I am using RTTI to loop trough attributes.

If I do this I get FALSE with the IS operator. I premise that "Attribute" is surely and absolutely "MyAttributeOne" class.

This happens when the module that declares MyAttributeOne is different than the module that is using MyAttributeOne, and the two modules have been compiled separately to have different RTTIs for the same type.  In this case, you would need to move MyAttributeOne into a separate Package that both modules can share with Runtime Packages enabled, so that only 1 RTTI exists for MyAttributeOne between the modules.

  • Like 1

Share this post


Link to post
14 hours ago, Uwe Raabe said:

Check if you have more than one declaration of MyAttributeOne.

Yes. It is.

I hadn't noticed before.

Thanks

Share this post


Link to post
4 hours ago, pcplayer99 said:

if Attribute Is MyAttributeOne then

vs

if (Attribute Is MyAttributeOne) then

There is no functional difference between those two.

Share this post


Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×