Hi Dave,
Thanks for your advice. Sounds interesting. We definitely missed out that
we can store string ID as an attribute, instead of string itself.
I have another question, can we add custom attribute to the Type class,
instead of assembly itself?
Sure, that would be the usual way to do it.
What I basically want is attach string ID
attribute to the Type and get Display Name of the type without first
instantiating it. There is a TypeAttributes object "Attributes "
representing the attribute set of the Type. But it doesn't seem to me much of help.
It's really not hard to use custom attributes. Consider this simple example
that basically implements something like what you want (minus some error
checks):
--------------------------------------------------------------------
MyComponent.txt .
Compile with: resgen MyComponent.txt
--------------------------------------------------------------------
MyComponent=Thi s is the super cool component
--------------------------------------------------------------------
CustAttr.cpp
Compile with:
cl /clr CustAttr.cpp /link /assemblyresourc e:MyComponent.r esources
--------------------------------------------------------------------
#using <mscorlib.dll >
using namespace System;
using namespace System::Collect ions;
using namespace System::Reflect ion;
using namespace System::Resourc es;
//
// Our custom attribute
//
public __gc class DisplayNameAttr ibute : public Attribute
{
private:
String* resname_;
public:
DisplayNameAttr ibute(String* resourceName)
: resname_(resour ceName)
{
}
String* GetDisplayName( Type* type) {
ResourceManager * mgr = new ResourceManager (type);
return mgr->GetString(resn ame_);
}
};
//
// Component using the attribute
//
[ DisplayName(S"M yComponent") ]
public __gc class MyComponent
{
// ...
};
//
// Class used to find components in a
// given assembly. Returns a Hashtable
// with the component display name
// and the type implementing it
//
public __gc class ComponentFinder
{
public:
static Hashtable* FindAll(Assembl y* assembly)
{
Hashtable* components = new Hashtable();
Type* types[] = assembly->GetTypes();
for ( int i=0; i < types->Length; i++ )
{
if ( types[i]->IsAbstract )
continue;
DisplayNameAttr ibute* dnattr[] =
dynamic_cast<Di splayNameAttrib ute*[]>(
types[i]->GetCustomAttri butes(__typeof( DisplayNameAttr ibute),
false)
);
if ( dnattr != 0 && dnattr->Length > 0 ) {
components->Add(dnattr[0]->GetDisplayName (types[i]), types[i]);
}
}
return components;
}
};
//
// get list of components in current
// assembly and print them
//
int main()
{
Assembly* assembly = Assembly::GetEx ecutingAssembly ();
Hashtable* components = ComponentFinder ::FindAll(assem bly);
IDictionaryEnum erator* e = components->GetEnumerator( );
while ( e->MoveNext() )
{
Console::WriteL ine(S"{0} - {1}", e->Key, e->Value);
}
}
--
Tomas Restrepo
to****@mvps.org