开发学院软件开发C语言 Effective C# 原则42:使用特性进行简单的反射 阅读

Effective C# 原则42:使用特性进行简单的反射

 2009-02-19 08:17:38 来源:WEB开发网   
核心提示: // Expanded from the first code sample:// Find the types in the assemblyforeach( Type t in asm.GetExportedTypes( ) ){if (t.GetCustomAttributes(ty

// 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 );
}

上一页  1 2 3 4 5  下一页

Tags:Effective 原则 使用

编辑录入:爽爽 [复制链接] [打 印]
[]
  • 好
  • 好的评价 如果觉得好,就请您
      0%(0)
  • 差
  • 差的评价 如果觉得差,就请您
      0%(0)
赞助商链接