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=This is the super cool component
--------------------------------------------------------------------
CustAttr.cpp
Compile with:
cl /clr CustAttr.cpp /link /assemblyresource:MyComponent.resources
--------------------------------------------------------------------
#using <mscorlib.dll>
using namespace System;
using namespace System::Collections;
using namespace System::Reflection;
using namespace System::Resources;
//
// Our custom attribute
//
public __gc class DisplayNameAttribute : public Attribute
{
private:
String* resname_;
public:
DisplayNameAttribute(String* resourceName)
: resname_(resourceName)
{
}
String* GetDisplayName(Type* type) {
ResourceManager* mgr = new ResourceManager(type);
return mgr->GetString(resname_);
}
};
//
// Component using the attribute
//
[ DisplayName(S"MyComponent") ]
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(Assembly* assembly)
{
Hashtable* components = new Hashtable();
Type* types[] = assembly->GetTypes();
for ( int i=0; i < types->Length; i++ )
{
if ( types[i]->IsAbstract )
continue;
DisplayNameAttribute* dnattr[] =
dynamic_cast<DisplayNameAttribute*[]>(
types[i]->GetCustomAttributes(__typeof(DisplayNameAttribute ),
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::GetExecutingAssembly();
Hashtable* components = ComponentFinder::FindAll(assembly);
IDictionaryEnumerator* e = components->GetEnumerator();
while ( e->MoveNext() )
{
Console::WriteLine(S"{0} - {1}", e->Key, e->Value);
}
}
--
Tomas Restrepo
to****@mvps.org