Dynamically create objects from string when implementing runtime

zhaozj2021-02-17  77

Creating a type of creating objects at runtime, or even create a desired object with a string indicating the name of the type, the reflection mechanism of .NET FRAMWORK has brought us a solution to the problem. Here, if you only need to create a general object, we can implement it via System.Activator, and more complicated we can implement the constructor.

Reflecting reflection is an important mechanism in .NET, through reflection, you can get every type of .NET, including classes, structures, delegates, interfaces, enumerations), including methods, properties, events, and constructors, etc. You can also get the name, qualifier, and parameters of each member. If you have a reflection, you can refer to each type. If you get the information of the constructor, you can create objects directly, even if the type of this object is not known when compiling.

///

/// CreateNewControls generates a control according to the name of the space, the type string, the size, and position to dynamically generate a control

///

/// Container loaded by the control

/// Generated control instance name

/// The generated control type string is such as (TextBox, Button, etc.)

/// Control size

/// The location of the control

/// Generation Control Instances

Private Control CreateNewTrols (Control.ControlCollection TargetControl, String CTLName, Type CTLTYPE, System.drawing.Size Ctlsize, System.drawing.Point CTLLOCATION)

{

Control TOCREATE;

TOCREATE = (Control) System.activator.createInstance (CTLTYPE);

TOCREATE.NAME = CTLNAME;

TOCREATE.SIZE = CTLSIZE;

TOCREATE.LOCATION = CTLOCATION;

TargetControl.Add (TOCREATE);

Return Tocreate;

}

Size cbsize = new size (160, 40);

Point Cbpoint = New Point (64, 206);

Control c1 = CreateNewControls (this.Controls, "control1", Type.GetType ( "System.Windows.Forms.CheckBox, System.Windows.Forms, Version = 1.0.5000.0, Culture = neutral, PublicKeyToken = b

77A

5C

561934E089 "), CBSIZE, CBPOINT

C1.Text = "Check Box";

.ne tframework 1.1, Type.gettype ("System.windows.Forms.Checkbox, System.Windows.Forms, Version = 1.0.5000.0, Culture = NEUTRAL, PUBLICKEYTOKEN = B77A

5C

561934E089 ").

How do we get the version and strong name of the Windows.form assembly used? You can use the syntax such as gettype (checkbox). Once this information is obtained, we can use this information for any other control because they all come from the same version of the Windows.Forms assembly.

转载请注明原文地址:https://www.9cbs.com/read-31267.html

New Post(0)