I'm doing a runtime assembly load, but i don't know the names of any classes or methods. I wan't to list all classes in my assembly with their declared methods, not those inherited from System.Object.
This is the code:
string str = "";
Assembly assembly = Assembly.LoadFile(@"c:\components.dll");
foreach (Type type in assembly.GetTypes())
{
if (type.IsClass == true)
{
str += type.Name + "\n";
MethodInfo[] methodInfo = type.GetMethods(BindingFlags.DeclaredOnly);
foreach (MethodInfo mi in methodInfo)
{
str += "\t" + mi.Name + "\n";
}
}
}
MessageBox.Show(str);
This is the components.dll:
public class component01
{
public string myName = "component01";
public string getMyName()
{
return myName;
}
}
public class component02
{
public string myName = "component02";
public string getMyName()
{
return myName;
}
}
The result:
component01
component02
And if i remove the bindingflag:
component01
getMyName
ToString
Equals
GetHashcode
GetType
component02
getMyName
ToString
Equals
GetHashcode
GetType
I only want the getMyName
method shown.
You can use a Type object's methods, fields, properties, and nested classes to find out everything about that type. Use Assembly. GetType or Assembly. GetTypes to obtain Type objects from assemblies that have not been loaded, passing in the name of the type or types you want.
At runtime, when you use a type from a referenced project for the first time, the CLR looks in the application directory for the DLL file with the same name and version it expects. It then loads that assembly into the process. This is also called binding to the assembly.
Loads an assembly given its AssemblyName. The assembly is loaded into the domain of the caller using the supplied evidence. Loads the assembly with a common object file format (COFF)-based image containing an emitted assembly. The assembly is loaded into the application domain of the caller.
The reflection-only load context allows you to examine assemblies compiled for other platforms or for other versions of the . NET Framework. Code loaded into this context can only be examined; it cannot be executed. This means that objects cannot be created, because constructors cannot be executed.
I think you're looking for the flags:
BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly
You may want to put in BindingFlags.NonPublic
as well, depending on your requirements.
I would also point out that with deeper inheritance hierarchies, types can inherit members from base-types other than System.Object
. If you want to keep those, but not the ones originally declared on object
, you could:
BindingFlags.DeclaredOnly
flag for the GetMethods
call. Only include methods for which:
methodInfo.GetBaseDefinition().DeclaringType != typeof(object)
Of course, you may need a different filter if your definition of "declared" method were more complicated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With