[ Team LiB ] |
Recipe 12.5 Finding Members Within an InterfaceProblemYou need to find one or more members, with a specific name or a part of a name that belongs to an interface. SolutionUse the same technique outlined in Recipe 12.4, but filter out all types except interfaces. The first overloaded version of the FindIFaceMemberInAssembly method finds a member specified by the memberName parameter in all interfaces contained in an assembly. Its source code is: public static void FindIFaceMemberInAssembly(string asmPath, string memberName) { // delegate to the interface based one passing blank FindIFaceMemberInAssembly(asmPath, memberName, "*"); } The second overloaded version of the FindIFaceMemberInAssembly method finds a member in the interface specified by the interfaceName parameter. Its source code is: public static void FindIFaceMemberInAssembly(string asmPath, string memberName, string interfaceName) { Assembly asm = Assembly.LoadFrom(asmPath); foreach(Type asmType in asm.GetTypes( )) { if (asmType.IsInterface && (asmType.FullName.Equals(interfaceName) || interfaceName.Equals("*"))) { if (asmType.GetMember(memberName, MemberTypes.All, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.IgnoreCase).Length > 0) { foreach(MemberInfo iface in asmType.GetMember(memberName, MemberTypes.All, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.IgnoreCase)) { Console.WriteLine("Found member {0}.{1}", asmType.ToString( ),iface.ToString( )); } } } } } DiscussionThe FindIFaceMemberInAssembly method operates very similarly to the FindMemberInAssembly method of Recipe 17.3. The main difference between this recipe and the one in Recipe 12.4 is that this method uses the IsInterface property of the System.Type class to determine whether this type is an interface. If this property returns true, the type is an interface; otherwise, it is a noninterface type. This recipe also makes use of the GetMember method of the System.Type class. This name may contain a * wildcard character at the end of the string only. If the * wildcard character is the only character in the name parameter, all members are returned. If you'd like to do a case-sensitive search, you can omit the BindingFlags.IgnoreCase flag from the call to Type.GetMember. See AlsoSee Recipe 12.11; see the "Assembly Class," "BindingFlags Enumeration," and "MemberInfo Class" topics in the MSDN documentation. |
[ Team LiB ] |