开发者

Why does Assembly.GetType() Reflect the Reflections Assembly when a Different Assembly is Loaded?

I am new to using Reflection but trying to understand the behavior of GetType()

I have the following:

assembly = Assembly.LoadFile(@"D:\ObjectRelations.dll");             
Type type = assembly.GetType("ObjectRelations.JSHierarchyBuilder");               
MethodInfo[] methods = type.GetMethods();

try                  
{       
 foreach (MethodInfo method in methods)
 {
     .... List Some info, etc.
 }
}
catch ...

While this yields the expected output for what's contained in my Assembly, using an alternative of

     Type type = assembly.GetType();

Gives me the methods associated with the Reflection Assembly and not the Assembly that is designated in the LoadFile method which isn't really what I'd expected or would have thought would be a practical behavior; else why would I need to specify any file to load at all if the return Type would be that of the Reflection Assembly. Kinda wierd to me.

Anyway, if this is correct; and seeing that my 1st example worked as intended. Then how would one acquire any information for example "The Methods" of an Assembly without precisely knowing the Namespace/and or Class Name of the Assembly which could be different than the name of the Assembly?

I am presuming that Reflection should allow you to examine this type of information even if you have no foreknowledge of what's under the hood of an assembly and that the Dynamic aspect of instantiating objects at runtime isn't the开发者_JAVA百科 "only" benefit.

Could someone plz expound? Or am I going about this all wrong.


When you call:

 Type type = assembly.GetType();

You're actually calling the Object.GetType() method on Assembly, which returns typeof(Assembly).

I suspect you wanted:

 Type[] types = assembly.GetTypes();

This will return the collection of all types defined within the assembly.

The difference here is that, in the first case you're asking the variable (assembly) for it's type, which is Assembly. In the second, you're asking the instance for the list of types that are defined within the assembly itself.


You're calling the standard Object.GetType() method, which gives you the runtime type of the instance it's called on.

You might be looking for Assembly.GetTypes() (plural)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜