jeudi 5 mars 2015

Checking if object has custom attribute

I've got a recursive deep-copy function to create new instances of objects. To improve my function's capabilities I want to put some kind of <noCopy> custom attribute on some values within my object to prevent them from beeing copied


an object to be copied may look like this:



public Class CDatabase
public var1 as double
private var2 as CSomeObject
<noCopy> private var3 as double
<noCopy> private var4 as CSomeObject
...
end class


my recursive function looks like this:



public shared Function Copy(originalObject as Object) as Object

if originalObject = nothing then
return nothing
end if

if Attribute.IsDefined(originalObject.GetType, GetType(NoCopy)) 'This does not work
return nothing
end if

~ do other recursive stuff ~

return cloned object
end function


my attribute is defined as followed:



<System.AttributeUsage(System.AttributeTargets.All)>
Public Class NoCopy
Inherits System.Attribute
End Class


and I call my clone function like that:



public Class Example

dim original as Database
dim clone as Database
clone = original.Copy

'This one returns true
Dim test As Boolean = Attribute.IsDefined(original.GetType.GetMember("var3")(0), GetType(NoCopy))

end class


when I try to get the attributes of originalObject I always get a false return value. But when I do it by referring directly to the object I get a positive result.






Aucun commentaire:

Enregistrer un commentaire