Dynamic Reflection--load,loadfrom and LoadFile

Source: Internet
Author: User

Ask

Suppose you have a class library file Librarya, which has a classa, and the assemblyname of the class is "Librarya" (the compiled file is LibraryA.dll). There is also a LibraryB.dll class library file, where AssemblyName is the same as its namespace, and its reference is LibraryA.dll. Their code is as follows:

[C #]

"LibraryA.dll"

Namespace A
{
public class ClassA
{
Public ClassA ()
{
Console.WriteLine ("The constructor for the successful execution of ClassA. ");
}
}
}

"LibraryB.dll"

Using Librarya;

Namespace Libraryb
{
public class ClassB
{
Public ClassA Getclassa ()
{
return new ClassA ();
}

Public ClassB ()
{
Console.WriteLine ("The constructor for the successful execution of CLASSB. ");
}
}
}

[VB.net]

"LibraryA.dll"

Namespace A
Public Class ClassA
Public Sub New ()
Console.WriteLine ("The constructor for the successful execution of ClassA. ")
End Sub
End Class
End Namespace

"LibraryB.dll"

Imports Librarya

Namespace Libraryb
Public Class ClassB
Public Function Getclassa () as ClassA
Return New ClassA ()
End Function

Public Sub New ()
Console.WriteLine ("The constructor for the successful execution of CLASSB. ")
End Sub
End Class
End Namespace

Now suppose you have a console program that contains the main function, which also references Librarya. Requirements:

1. Try to use the reflection method to run the Librarya constructor.

2. Try to run the Getclassa method using the dynamic load method (only allow loading LibraryB.dll, assuming it is located in the D:\ directory).

Assuming that the D:\ There are two folders (F1 and F2). Copy the original LibraryB.dll in the F1, and then in F2 copy the modified LibraryB.dll (that is, the constructor output is changed to "Execute CLASSB successfully", and then recompile the copy into F2). I dynamically load two different paths in the console main program, but the same version of LibraryB.dll. What is the result after running the following program?

[C #]

Assembly asm = Assembly.LoadFrom (@ "D:\f1\LibraryB.dll");
Asm. CreateInstance ("LIBRARYB.CLASSB");
ASM = Assembly.LoadFrom (@ "D:\f2\LibraryB.dll");
Asm. CreateInstance ("LIBRARYB.CLASSB");

[VB.net]

Dim asm as Assembly = Assembly.LoadFrom (@ "D:\f1\LibraryB.dll")
Asm. CreateInstance ("LIBRARYB.CLASSB")
ASM = Assembly. LoadFrom (@ "D:\f2\LibraryB.dll")
Asm. CreateInstance ("LIBRARYB.CLASSB")

"Wrong answer."

1)

[C #]

Assembly asm = assembly.load ("A");
Asm. CreateInstance ("A.classa");

[VB.net]

Dim asm as Assembly = Assembly.Load ("A")
Asm. CreateInstance ("A.classa")

Reason: Load needs a assemblyname, which is the name of namespace. Then the CreateInstance needs a "namespace name. Class name".

2)

[C #]

Assembly asm = assembly.loadfile (@ "D:\LibraryB.dll");
Asm. CreateInstance ("Libraryb.classb"). GetType (). GetMethod ("Getclassa");

[VB.net]

Dim asm as Assembly = Assembly.loadfile ("D:\LibraryB.dll")
Asm. CreateInstance ("Libraryb.classb"). GetType (). GetMethod ("Getclassa")

3) output two lingo--

The constructor for the successful execution of the CLASSB.

The constructor update for CLASSB was executed successfully.

"Positive Solution"

First question: Beginners do not seem to differentiate between "AssemblyName" and "Namespace"-indeed, few teachers teach them to differentiate between the two. AssemblyName is the "assembly" name, which is a special unique identifier used to log program information that is recognized by the underlying CLR invocation of. Net; namespace is intended for program designers so that customers can archive different classes, so namespace a similar folder, Each class is similar to a file in a folder, and assembly is equivalent to the "volume label" of a hard disk.

therefore, Assembly.Load The first parameter required is the AssemblyName , and Namespace There is no direct link. You can modify AssemblyName as needed (method: Right-click the project, select "Properties", you can see it on the "Programs (application)" panel).

The second and third questions are actually investigating how to properly use LoadFile and LoadFrom to dynamically load the specified class library.

Second question: The error code will result in a "Cannot find load file" similar error, The reason for this is that LibraryB.dll references LibraryA.dll, but if LoadFile is used, the assembly LibraryA.dll is not automatically loaded when LibraryB.dll is dynamically reflected, but "Getclassa" method requires the use of classes in Librarya. The error is subsequently raised. The LoadFrom method should be used to allow the referenced DLLs to be loaded in the same way.

Third question and second question instead, investigate loadfile and LoadFrom load an assembly, but in a different location of the class library (note: Here "assembly is the same" refers to the source code based on a slight modification to form a copy of the DLL).

Third question: LoadFile load the class library, as long as the absolute or relative to the house path of the class library, it is always loaded and this is the same, but the LoadFrom is different-if you encounter the same assembly's class library file, the first time the load will prevail. Therefore, the output of the two words are "successful execution of the ClassB constructor." ”。

Summary

1 ) AssemblyName and the Namespace not the same thing, AssemblyName is for . NET to use; Namespace is the namespace of the customer-defined "archive" class. assembly.load needs the former, but when the project is created,VS By default is the same.

2 ) LoadFile just load the assembly file, but reflection is limited to methods, properties, and so on in the current assembly itself, and if you need to reflect the external assembly to which it is referenced, you must use the LoadFrom .

3 ) LoadFrom The same assembly file is loaded only for the first time, so only the first result is returned; to reflect different paths but the same assembly file, you must use the LoadFile .

Expand

An "assembly" is a collection of one or more type definition files and resource files , generally when a complete is created. NET program (either C # or vb.net), the VS default produces an assembly for it. Assemblies typically contain information about the program (such as the version number of the program), which are stored in a file called "Assembly.cs" (which is AssemblyInfo.vb in vb.net). If you double-click to open the file, we can see one or two (comment delete)--

[C #]

[Assembly:assemblytitle ("CSharp")]
[Assembly:assemblydescription ("")]
[Assembly:assemblyconfiguration ("")]
[Assembly:assemblycompany ("Microsoft IT")]
[Assembly:assemblyproduct ("CSharp")]
[Assembly:assemblycopyright ("Copyright©microsoft IT 2011")]
[Assembly:assemblytrademark ("")]
[Assembly:assemblyculture ("")]
[Assembly:assemblyversion ("1.0.0.0")]
[Assembly:assemblyfileversion ("1.0.0.0")]

[VB.net]

<assembly:assemblytitle ("CSharp") >
<assembly:assemblydescription ("") >
<assembly:assemblyconfiguration ("") >
<assembly:assemblycompany ("Microsoft IT") >
<assembly:assemblyproduct ("CSharp") >
<assembly:assemblycopyright ("Copyright©microsoft IT") >
<assembly:assemblytrademark ("") >
<assembly:assemblyculture ("") >
<assembly:assemblyversion ("1.0.0.0") >
<assembly:assemblyfileversion ("1.0.0.0") >

Here's how to read this data:

1) AssemblyVersion is the version number of the program. In general, by reading the version number of the program to understand whether the program is up-to-date, many updates are often through similar means or methods to update the program. to read the version number of a current program, we Assembly.getname method gets Version property.

[C #]

AssemblyName an = assembly.getexecutingassembly (). GetName ();
Console.WriteLine (An. Version);

[VB.net]

Dim an as AssemblyName = assembly.getexecutingassembly (). GetName ()
Console.WriteLine (An. Version)

GetExecutingAssembly is a assembly entity that gets the program that is currently running. If you want to read the version number of a specified program, we can use the Assembly.loadfile or Assembly.LoadFrom Load a DLL or a EXE file, and then through GetName Get AssemblyName , and then follow the same method as above Version A class of attributes is available.

By the way, "AssemblyName". An "assembly" name can be used before the "expand" analysis. As a matter of fact. NET defines it as a class, can be used specifically to get Culture (corresponding to assemblyculture ), name (meaning "assembly name" of the current program) and Version (refers to AssemblyVersion ) etc. , where Version also includes " Major (major version number), " Minor (minor version number), Build (compile version number) and " Revision (Fixed version number) . They work by:

1) Major (motherboard number) +minor (minor version): Two compositions for external release, to inform customers of the current version of the program. In general,Major represents a "milestone" program update (such as Windows98 to XP, then Major will have an impact, since 1), while Minor is a local major update in the current program (such as adding and removing functions based on the original program). , or if a bug is found to be patched, etc.).

2) Build (compiled version number): Internally informs the developer or tester that the program is currently compiled from start to finish, total compile times (each recompile this self-increment 1 ).

3) Revision(Fixed version number): Every time a Bug is found in the test, this version number on the original base plus 1 , which indicates how many BUG fixes have gone through the total from start to finish .

AssemblyVersion and assemblyfileversion generally need to be consistent. The former is being. NET internal reflection is used, the latter is external and can be viewed by right-clicking the = property. For example, to view the WORD2010 program we can understand the following information:

The first "14" indicates that the word family has experienced the development of 14 different "milestone" versions, the second "0" indicates that no significant additions or deletions have been made to office2010, and "5123" indicates that the version of the Word program has been compiled 5,123 times, and "5000" indicates a total of 5,000 bug fixes from start to finish.

In addition to being able to see the file information in Assembly.cs, we can also get the same information by right-clicking a csproj (vbproj in vb.net) and "Properties" and "Applications (application)":

The default major version number is 1, the rest is 0, and the bottom one "check box" is "Automatically revision version number self-increment 1", that is, each time the external release, the program's revision will be added on the original Basis 1.

2) In addition to the version number, the rest of the assembly information (such as assemblytitle) can be obtained in this way:

[C #]

AssemblyTitleAttribute at = (AssemblyTitleAttribute) Assemblytitle.getcultureattribute (
Assembly.getexecutingassembly (), typeof (Assemblytitle)
);
Console.WriteLine (at. Title);

[VB.net]

   Dim at As AssemblyTitleAttribute = DirectCast (
Assemblytitleattribute.getcustomattribute (assembly.getexecutingassembly (), GetType (AssemblyTitleAttribute)
), AssemblyTitleAttribute) Console.WriteLine (at. Title)


More generally, because these are "attribute" classes in the assembly file (the suffix attribute is omitted). So we can use the reflection method to get them, pseudo code is described as follows:

[C #]

Xxxattribute Variable name = Xxxattribute.getcustomattribute (Assembly entity object , typeof (Xxxattribute));

Variable name . Properties ;

[VB.net]

Dim Variable name As xxxattribute== xxxattribute.getcustomattribute (Assembly entity object , typeof (Xxxattribute))

Variable name . Properties

A few notes:

1) " XXX "represents the corresponding Assembly in the file, " Assembly: "That part of the back.

2) attributeculture and the attributeversion cannot be obtained using the method above, only using the AttributeName method. Because they are generated by the compiler, they are not directly visible to external customers through the "right-click" + "Properties" method.

Dynamic Reflection--load,loadfrom and LoadFile

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.