Effective C# 原则42:使用特性进行简单的反射
2009-02-19 08:17:38 来源:WEB开发网// Expanded from the first code sample:
// Find the types in the assembly
foreach( Type t in asm.GetExportedTypes( ) )
{
if (t.GetCustomAttributes(
typeof( CommandHandlerAttribute ), false).Length > 0 )
{
// Found a command handler type:
ConstructorInfo ci =
t.GetConstructor( new Type[0] );
if ( ci == null ) // No default ctor
continue;
object obj = ci.Invoke( null );
PropertyInfo [] pi = t.GetProperties( );
// Find the properties that are command
// handlers
foreach( PropertyInfo p in pi )
{
string menuTxt = "";
string parentTxt = "";
object [] attrs = p.GetCustomAttributes(
typeof ( DynamicMenuAttribute ), false );
foreach ( Attribute at in attrs )
{
DynamicMenuAttribute dym = at as
DynamicMenuAttribute;
if ( dym != null )
{
// This is a command handler.
menuTxt = dym.MenuText;
parentTxt = dym.ParentText;
MethodInfo mi = p.GetGetMethod();
EventHandler h = mi.Invoke( obj, null )
as EventHandler;
UpdateMenu( parentTxt, menuTxt, h );
}
}
}
}
}
private void UpdateMenu( string parentTxt, string txt,
EventHandler cmdHandler )
{
MenuItem menuItemDynamic = new MenuItem();
menuItemDynamic.Index = 0;
menuItemDynamic.Text = txt;
menuItemDynamic.Click += cmdHandler;
//Find the parent menu item.
foreach ( MenuItem parent in mainMenu.MenuItems )
{
if ( parent.Text == parentTxt )
{
parent.MenuItems.Add( menuItemDynamic );
return;
}
}
// Existing parent not found:
MenuItem newDropDown = new MenuItem();
newDropDown.Text = parentTxt;
mainMenu.MenuItems.Add( newDropDown );
newDropDown.MenuItems.Add( menuItemDynamic );
}
更多精彩
赞助商链接