In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
VB.NET dynamic code generation skills, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain in detail for you, people with this need can come to learn, I hope you can gain something.
The discussion here will also focus on these two situations. The first is when programmers need to dynamically build a control and attach code to it. For example, you may want to create a list of links, but you don't know how many links need to be created or what kind of data will appear in the links. The second is when programmers need to define code to reflect special requirements. For example, you may want to execute code that reflects the user's system configuration.
Things like the above certainly don't happen every day. In fact, they only appear in extraordinary circumstances. However, as a programmer, you should still be aware that .NET provides a solution to dynamic situations. With the right skills, you can write applications that can handle dynamic situations flexibly.
Use dynamic controls
Many programmers always encounter a time when they need to create controls dynamically. In the example we show, the programmer adds LinkLabels to FlowLayoutPanel. Maybe you can use this setting to record and save the values of commonly used URL, files, network addresses, or other resource locations. This example doesn't really save the link, but you can use the XML serialization feature to save it.
Each time the user clicks the Test button, the sample code dynamically creates a new LinkLabel control. The real demo code is not complicated. Example 1 shows everything you normally need to do to create such controls and put them into FlowLayoutPanel,lstLabel.
Example 1: add a new link to FlowLayoutPanel
Private Sub btnTest_Click () Handles btnTest.Click 'Create a link. Dim NewLink As LinkLabel = New LinkLabel () 'Add some properties to it. NewLink.Text = DateTime.Now. ToLongTimeString () 'Set the click event handler. AddHandler NewLink.Click, AddressOf NewLink_Click 'Place the button on the form. LstLinks.Controls.Add (NewLink) End Sub
As you might expect, the code starts by creating a new LinkLabel and assigning some values to it. This example uses the current time. Your code may be able to access a real resource.
Notice that the code also assigns a handler to the linked Click event. You have to use the AddHandler technique in the example, because the normal Handles keyword path doesn't work. On the one hand, you don't know the name of the control when you design the application. Even if you specify a name for the control, you don't know how many controls the user will create, so there is no way to know how many handlers will be created. The code for handlers is similar to control code, so there is no need to create multiple handlers. The processing code used for this example is shown in example 2. Example 2: handling dynamic control click events
Private Sub NewLink_Click (_ ByVal sender As System.Object, ByVal e As System.EventArgs) 'Verify that you actually have a LinkLabel If Not sender.GetType () Is GetType (LinkLabel) Then MessageBox.Show ("Wrong control type provided!") Return End If 'Convert the input sender to a Button. Dim ThisLink As LinkLabel = sender 'Show that we have the correct button. MessageBox.Show ("You created this link at:" + ThisLink.Text) End Sub
You may have noticed that the event handler in example 1 uses a loose representation-- it doesn't take the ByVal sender as the System.Object, nor does it take ByVal e as the System.EventArgs parameter because it doesn't need both. However, when you create an event handler to dynamically create a control, you usually need to take the ByVal sender as a System.Object parameter, which means that you include both.
Some programmers have an error when creating an event handler that does not check the type of the incoming control. The sender object may contain multiple choices, and if the event handler is not set for the event handling type, then you will face more choices. Our sample code starts by checking the type of the incoming control object. In this way, the transmitter will not be like the code shown below:
Private Sub btnTest2_Click () Handles btnTest2.Click 'Create a link. Dim NewButton As Button = NewButton () 'Add some properties to it. NewButton.Text = DateTime.Now.ToLongTimeString () 'Set the click event handler. AddHandler NewButton.Click, AddressOf NewLink_Click 'Place the button on the form. LstLinks.Controls.Add (NewButton) End Sub
This code creates a button in FlowLayoutPanel, which works in most cases unless the event handler does not act as shown by the button. If you are going to serve multiple control types, each control type requires a unique handling. You can use multiple event handlers or provide selection criteria for certain types.
The NewLink_Click () event handler converts the incoming sender to the specified type as usual, in this case LinkLabel. This code can access the LinkLabel property and interact in other ways. In our example, only one dialog box is shown that tells us when the link is created.
Use dynamic code
Creating a control at run time is a strategy adopted when the functionality of the application cannot be determined. However, dynamically creating controls is not suitable for all cases. Sometimes you have to create executable code, although your application runs to compensate for different configurations, different user needs, different environmental requirements, or other requirements. When the computer on which the application is running does not have controls, it is usually necessary to create dynamic code.
Fortunately, .NET provides us with a range of dynamic code options. For example, you can create an executable program that can run independently, or you can load a DLL and then execute a program that you want to run. When you need to demonstrate an external task, you can use options to execute, such as running a script-this DLL option is best suited for expanding existing application functionality.
You can run dynamic code from files or memory. You can use files when you need to run the code more than once. The check of the code can run the external file again without recompiling it. When you need to demonstrate multiple tasks, such as an installation request, you can use in-memory images.
Of course, we can also change the source code. For example, you can use strings to create code that needs to be used directly in the application. If you need the code to be highly flexible and the code itself is not very long, the advantage of this approach is significant. You can also create code from a file, just like VS. This method is most suitable for requirements that are relatively stable and do not require complex coding. The third option is to use Documentation Object Model to create code and use it as a series of CodeDom trees. The tree structure includes CodeCormpileUnits. This is like creating a XML file in DOM schema.
The way to create code dynamically is to check it out with examples. Example 3 shows a basic "Hello World" example. This example creates the code directly from the source code so you can see the whole process of running and generating an external executable.
Example 3: dynamic coding example
Private Sub btnTest3_Click () Handles btnTest3.Click 'Create a compiler. Dim Comp As VBCodeProvider = New VBCodeProvider () 'Define the parameters for the code you want to compile. Dim Parms As CompilerParameters = New CompilerParameters)'We do want to create an executable, rather than a DLL. Parms.GenerateExecutable = True 'The compiler will create an output assembly called Output. Parms.OutputAssembly = "Output" 'The compiler won't treat warnings as errors. Parms.TreatWarningsAsErrors = False 'Add any assembly you want to reference. Parms.ReferencedAssemblies.Add ("System.Windows.Forms.dll") 'Define the code you want to run. Dim SampleCode As StringBuilder = New StringBuilder () SampleCode.Append ("Imports System.Windows.Forms" + vbCrLf) SampleCode.Append ("Module TestAssembly" + vbCrLf) SampleCode.Append ("Sub Main ()" + vbCrLf) SampleCode.Append ("MessageBox.Show (" + Chr (34) + _ "Dynamically Created Code!" + Chr (34) + ") + vbCrLf) SampleCode.Append (" End Sub "+ vbCrLf) SampleCode.Append (" End Module "+ vbCrLf) 'Define the code to run. Dim Executable As CompilerResults = _ Comp.CompileAssemblyFromSource (Parms, SampleCode.ToString ()) 'Display error messages if there are any. If Executable.Errors.HasErrors Then For Each Item As CompilerError In Executable.Errors MessageBox.Show (Item.ErrorText) Next Else'If there aren't any error messages, start the 'executable. Process.Start ("Output") End If End Sub
At first you created a compiler Comp that uses VBCodeProvider. The older .NET version uses a different approach, but what we're talking about here is a new approach recommended by Microsoft.
In order to use the compiler, you must create parameters that describe the application. These parameters are similar to the parameters you created in VS, except that you can now define them. The code starts by setting GenerateExecutable to True, which means you need an EXE file instead of DLL.
The Parms.OutputAssembly attribute contains the name of the output file. You only need to provide this information when you want to create a file, instead of generating executable memory. If you ixiang generates a memory version of the executable, you can set the Parm.GenerateInMemory property to True.
Use the Parm.TreatWarningsAsErrors property to determine how to handle warning messages. The default setting makes it an error, which means that your application may not be able to compile it. Most programmers use the default setting, and although they have developed a program, they set it to False in the finished program.
Most applications require external DLL to function properly. Of course, you can't create any Windows form program that doesn't reference an external DLL. Typically, you use the Reference folder to accomplish this task. However, you can rely on the Parms.ReferencedAssemblies attribute when you create code dynamically. As shown below, just add the DLL you want.
Now that you have defined the project, you need to create the source code for it. As mentioned earlier, you can rely on an external file or DOM schema. Then, the example creates the code so you can see the whole process. Here is the original form of the code:
Imports System.Windows.Forms Module TestAssembly Sub Main () MessageBox.Show ("Dynamically Created Code!") End Sub End Module
This simple example shows a dialog box. Note the use of vbCrLf. If you do not use this method, the compiler will send you an error message. The vbCrLf entry plays the same role in this code as it does in program code, but in a different way.
From this point of view, you * will compile code with the Comp.CompileAsseblyFromSource () method. You can use this method when using DOM schemas and files. In all three cases, the compiler creates the output you requested with parameters and source code. The output of this operation appears in Executable and is of type CompilerResults.
Compilations fail more than programmers expect. No matter where you use dynamic coding techniques, you have to assume that there will be failures and solutions that deal with failures. In this case, the code looks for the error and displays it in the information box when the compilation fails. Otherwise, the code relies on the Process.Start () method to enable the executable.
Bottom line
Dynamic coding skills are not keys. You can also use it when you find a good static solution to a development problem. However, there is no feasible static solution in the cases we have listed, so choose dynamic coding techniques. In most cases, dynamic coding techniques are used to solve the following problems:
When the environment of ◆ users changes in an unforeseen way
◆ cannot control the installation of the user's computer
◆ users or applications add data elements that you want to execute with the control
When ◆ applications must perform installation tasks from a long time ago, and these tasks are closely related to the computer, environment, network, or other uncertainties
◆ applications perform processing-level tasks that depend on machine connections or other conditions.
Obviously, there are other situations where dynamic coding techniques can be used. The most important thing is to remember to consider using dynamic coding techniques whenever there is an unpredictable situation. Usually when there is a situation in the coding environment that static code cannot handle, we can use dynamic coding techniques.
Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.