Gets all types in the given matching the specified and the optional list . - CSharp System.Reflection

CSharp examples for System.Reflection:Assembly

Description

Gets all types in the given matching the specified and the optional list .

Demo Code

// Licensed under the Apache License, Version 2.0 (the "License"); 
using System.Reflection;
using System.Linq;
using System.Collections.Generic;
using System;/*  w  ww  .  j a  v a 2s .com*/

public class Main{
        /// <summary>
      /// Gets all types in the given <paramref name="assembly"/> matching the specified
      /// <paramref name="bindingFlags"/> and the optional list <paramref name="names"/>.
      /// </summary>
      /// <param name="assembly">The assembly in which to look for types.</param>
      /// <param name="bindingFlags">The <see cref="BindingFlags"/> used to customize how results
      /// are filters. If the <see href="Flags.PartialNameMatch"/> option is specified any name
      /// comparisons will use <see href="String.Contains"/> instead of <see href="String.Equals"/>.</param>
      /// <param name="names">An optional list of names against which to filter the result.  If this is
      /// <c>null</c> or left empty, all types are returned.</param>
      /// <returns>A list of all matching types. This method never returns null.</returns>
      public static IList<Type> Types( this Assembly assembly, Flags bindingFlags, params string[] names )
      {
         Type[] types = assembly.GetTypes();

         bool hasNames = names != null && names.Length > 0;
         bool partialNameMatch = bindingFlags.IsSet( Flags.PartialNameMatch );

         return hasNames
                   ? types.Where( t => names.Any( n => partialNameMatch ? t.Name.Contains( n ) : t.Name == n ) ).ToArray()
                   : types;
      }
      /// <summary>
      /// Gets all types in the given <paramref name="assembly"/> matching the optional list 
      /// <paramref name="names"/>.
      /// </summary>
      /// <param name="assembly">The assembly in which to look for types.</param>
      /// <param name="names">An optional list of names against which to filter the result.  If this is
      /// <c>null</c> or left empty, all types are returned.</param>
      /// <returns>A list of all matching types. This method never returns null.</returns>
      public static IList<Type> Types( this Assembly assembly, params string[] names )
      {
         return assembly.Types( Flags.None, names );
      }
}

Related Tutorials