Dynamic reflection-Load, LoadFrom, LoadFile, loadfromloadfile

Source: Internet
Author: User

Dynamic reflection-Load, LoadFrom, LoadFile, loadfromloadfile

[Question]

Assume that there is a class library file LibraryA with a ClassA. The AssemblyName of this class is "LibraryA" (the compiled file is LibraryA. dll ). In addition, there is a library file LibraryB. dll, where AssemblyName is the same as its namespace and it references LibraryA. dll. The Code is as follows:

[C #]

[LibraryA. dll]

Namespace
{
Public class ClassA
{
Public ClassA ()
{
Console. WriteLine ("The ClassA constructor is successfully executed. ");
}
}
}

[LibraryB. dll]

Using LibraryA;

Namespace LibraryB
{
Public class ClassB
{
Public ClassA GetClassA ()
{
Return new ClassA ();
}

Public ClassB ()
{
Console. WriteLine ("The ClassB constructor is successfully executed. ");
}
}
}

[VB. NET]

[LibraryA. dll]

Namespace
Public Class ClassA
Public Sub New ()
Console. WriteLine ("The ClassA constructor is successfully executed. ")
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 ClassB constructor is successfully executed. ")
End Sub
End Class
End Namespace

Assume that there is a console Program (including the Main function, which has also referenced LibraryA ). Requirements:

1. Try to use the Reflection Method to run the LibraryA constructor.

2. Try to use the Dynamic Loading Method (only LibraryB. dll can be loaded, assuming it is in the D: \ directory) and run the GetClassA method.

Assume that there are two folders (f1 and f2) under D ). Copy the original LibraryB in f1. dll copy; then copy the modified LibraryB in f2. dll (that is, the output of the constructor is changed to "a new version of the constructor that successfully executes ClassB", and then re-compiled and copied to f2 ). I dynamically load two different paths in the main program of the console, but the same version of LibraryB. dll. What is the result after the following programs run?

[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”)

[Incorrect 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 requires an AssemblyName, that is, the Namespace name. Then, a "namespace name. Class Name" is required for the CreateInstance ".

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 lines --

The ClassB constructor is successfully executed.

The new version of the ClassB constructor is successfully executed.

[Positive solution]

Question 1: beginners do not seem to distinguish between AssemblyName and Namespace. Indeed, few teachers teach them the difference between the two. AssemblyName is the name of an assembly. It is a special unique identifier used to record program information. the underlying CLR calls of. NET are identified. Namespace is intended for programmers, so that users can archive different classes. Therefore, Namespace is similar to folders, and each Class is similar to files in folders; as for Assembly, it is equivalent to the volume label of the hard disk.

Therefore,Assembly. LoadThe first parameterAssemblyName, AndNamespaceNo direct contact.You can modify the AssemblyName as needed (method: Right-click the project, select "properties", and you can see it on the "Application" Panel ).

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

Question 2: The error code will cause a similar error "file loading cannot be found" because LibraryB. dll references LibraryA. dll, but if LoadFile is used, LibraryB is dynamically reflected. dll does not automatically load the Assembly LibraryA. dll, but the "GetClassA" method needs to use the class in LibraryA. Then an error occurs. To load other referenced dll files together, use the LoadFrom method.

In contrast to the second question, the third question shows that LoadFile and LoadFrom load a class library with the same assembly but in different locations. (Note: the "same Assembly" here means slightly modifying the source code, build a copy of the dll ).

Question 3: LoadFile only loads the class library. If the absolute or relative path of the class library is specified, it is always loaded and prevails. But LoadFrom is different. If a class library file of the same assembly is encountered, take the first loading as the standard. Therefore, the two statements output are "successfully executed ClassB constructor .".

[Summary]

1)AssemblyNameAndNamespaceNot one thing,AssemblyNameYes. NETAndNamespaceIt is the namespace of the Custom "Archive" class.Assembly. LoadThe former is required, but when you create a project,VSBy default, the two are the same.

2)LoadFileOnly load the Assembly file, but the reflection is limited to the methods and attributes of the current Assembly. To reflect the referenced external assembly, you must useLoadFrom.

3)LoadFromIf the same Assembly file is loaded for the first time, only the first result is returned. To reflect different paths but the same Assembly file, you must useLoadFile.

[Expansion]

An assembly is a collection of one or more types of definition files and resource files.Generally, when a complete. NET Program (C # Or VB. NET) is created, VS generates an assembly for it by default. An Assembly generally contains several pieces of information about a program (such as the program version number), which are stored in a file called Assembly. cs (AssemblyInfo. VB in vb. NET. If you double-click to open the file, we can see that one or two (Delete comment )--

[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 2011")>
<Assembly: AssemblyTrademark("")>
<Assembly: AssemblyCulture("")>
<Assembly: AssemblyVersion("1.0.0.0")>
<Assembly: AssemblyFileVersion("1.0.0.0")>

The following describes how to read the data:

1) AssemblyVersion is the version number of the program. Generally, you can check whether the program is in the latest state by reading the program version number. Many update programs often update the program by using similar means or methods.To read the version number of the current program, we useAssembly. GetNameMethod acquisitionVersionAttribute.

[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 an Assembly entity that obtains the currently running program.To read the version number of a specified program, you can useAssembly. LoadFileOrAssembly. LoadFromLoadDllOrExeFile, and thenGetNameObtainAssemblyNameAnd then use the same methodVersionClass 1 attributesYou can.

By the way, "AssemblyName ". Through the analysis before "expansion", it can be a "assembly" name. In fact,. NET defines it as a class,It can be used to obtainCulture(CorrespondingAssemblyCulture),Name(The "assembly name" of the current program) andVersion(ReferenceAssemblyVersion) And other information,WhereVersionIt also includes"Major"(Main version),"Minor"(Minor version),"Build"(Build version) and"Revision"(Corrected version number). Their functions are as follows:

1)Major(Motherboard ID)+ Minor(Minor version): Two syntaxes are used for external release to inform the customer of the current program version. Generally,MajorIndicates a milestone program update (for exampleWindows 98ToXP, ThenMajorWill have an impact, auto-Increment1); AndMinorIt is used for local major updates in the current program (for example, adding or deleting functions on the basis of the original program, or discovering vulnerabilities for fixing.

2)Build(Build version number): Inform the developer or test personnel internally. Currently, the program has been compiled from the beginning to the completion of the whole process, and the total number of times of compilation (this auto-increment is calculated every time the program is re-compiled.1).

3)Revision(Corrected version number): each time there isBugDetected during internal testing. This version is based on the original version1Indicates the total number of completed tasks from start to finish.BugFix.

AssemblyVersion and AssemblyFileVersion must be consistent. The former is used by. NET internal reflection, and the latter is external, which can be viewed by right-clicking the attribute. For example, to view the Word2010 program, we can understand the following information:

The first "14" indicates that the Word family has developed 14 different "Milestone" versions, the second "0" indicates that the feature has not been significantly added or deleted in office2010 so far; "5123" indicates that the Word program of this version has been compiled for a total of 5123 times, "5000" indicates that a total of 5000 bugs have been fixed from the beginning to the end.

Besides. you can also right-click a csproj (VB. NET is vbproj), "property" => "Application" to get the same information:

By default, the primary version number is 1, and the remaining values are 0. The "check box" Below is "auto-incrementing by 1 for the Revision version number". That is to say, each time an external release is made, the Revision of the program will add 1 on the original basis.

2) Besides the version number, other 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)


Generally, these are all "feature" classes in the Assembly file (with the suffix Attribute omitted ). Therefore, we can use the reflection method to obtain them. The pseudocode is described as follows:

[C #]

XXXAttributeVariable name= XXXAttribute. GetCustomAttribute (AssemblyObject, Typeof (XXXAttribute ));

Variable name.Attribute;

[VB. NET]

DimVariable nameAs XXXAttribute = XXXAttribute. GetCustomAttribute (AssemblyObject, Typeof (XXXAttribute ))

Variable name.Attribute

Notes:

1)"XXX"Indicates the correspondingAssemblyFileAssembly:.

2)AttributeCultureAndAttributeVersionThe preceding method cannot be used for obtaining data.AttributeNameMethod. Because they are generated by the compiler, they are not directly output for external customers to pass the "right-click"=>"Attribute" method can be seen directly.

Related Article

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.