Classic Tutorial: Creating an instance of a class with. Net

Source: Internet
Author: User
Tags count end net requires string

Read a lot of online about dotnet dynamic Create class instances of the article, I want to sum up here, in fact, the method is very simple, is to use "Activator.CreateInstance". However, this method requires the type of the class to be created as an argument, and in order to obtain that parameter, [Assembly] can be used. GetType method, this method requires only the name (name string) of the class to be created, and the final question is to obtain the assembly in which the class resides. This solves the problem of how to get the assembly that contains the class that you want to create.

You can refer to the http://www.cnblogs.com/ShadowK/archive/2006/11/14/560131.html, a lot of text wrote a relatively complete dynamic construction of the Class Designer. In fact, there can be an easier way to get the assembly, and here's what I do.

Using Microsoft.VisualBasic.VBCodeProvider (), if C # can be CSharpCodeProvider (), compile the class file into a DLL file, and then use [Assembly]. LoadFrom ("The absolute path of the DLL") loads the DLL. This allows us to avoid complex code that creates DLLs and type. I told my project team members This example, after emphasizing to open the mind, simple is perfect, always try to find an easy way to achieve, customers will never for our complex code to spend a penny more.

1. How to perform a compilation task:

The following are the referenced contents:
The public Shared function compileexecutable () function compileexecutable (ByVal sourceName As String, ByVal DllPath as String, ByRef Returndllname as String) as Boolean
Dim sourcefile as FileInfo = New FileInfo (sourceName)
Dim provider as CodeDomProvider = Nothing
Dim Compileok as Boolean = False
' Select Code provider based on the extension of the original file
If sourceFile.Extension.ToUpper (CultureInfo.InvariantCulture) = ". CS" Then
Provider = New Microsoft.CSharp.CSharpCodeProvider ()
ElseIf sourceFile.Extension.ToUpper (CultureInfo.InvariantCulture) = ". VB "Then
Provider = New Microsoft.VisualBasic.VBCodeProvider ()
Else
Console.WriteLine ("Original file must contain. cs or. vb extension")
End If
If not provider are nothing Then
' Construct the full path of the DLL file
Dim dllName as String = String.Format ("{0}\{1}.dll", _
DllPath, _
SourceFile.Name.Replace (".", "_"))
Returndllname = DllName
Dim cp as CompilerParameters = New CompilerParameters ()
' Set compilation control parameters
Cp. GenerateExecutable = False to generate DLL, if true to generate EXE file
Cp. outputassembly = DllName
Cp. GenerateInMemory = False
Cp. TreatWarningsAsErrors = False
' Invoke the compilation method to compile the original code file into a DLL
Dim cr as CompilerResults = Provider.compileassemblyfromfile (cp, _
SourceName)
If Cr. Errors.Count > 0 Then
' Show compilation errors
Console.WriteLine (Compile error {0} compiled to {1}), _
SourceName, Cr. pathtoassembly)
Dim CE as CompilerError
For all CE in CR. Errors
Console.WriteLine ("{0}", CE. ToString ())
Console.WriteLine ()
Next CE
Else
' Shows the success of the compilation message
Console.WriteLine ("Original file {0} compiled into {1} completed successfully.", _
SourceName, Cr. pathtoassembly)
End If
' Returns the result of the compilation
If Cr. Errors.Count > 0 Then
Compileok = False
Else
Compileok = True
End If
End If
Return Compileok
End Function

2. Compile the DLL and dynamically create instances of the class. (The original file for this class is the Class1.vb file, placed in the App_Code folder of website, and can be placed in any physical location when used in practice.) )

The following are the referenced contents:
Dim strsourcefilename as String = Server.MapPath ("~/app_code/class1.vb") ' Full path to ' class file
Dim Strdllpath as String = Server.MapPath ("~/app_code") ' where the compiled DLL file is stored
Dim strdllname as String = "" "DLL's full path (return value)
Compileexecutable (Strsourcefilename, Strdllpath, Strdllname) ' compiles the original file as a DLL file
Dim A As [Assembly] = [Assembly]. LoadFrom (strdllname) ' Load DLL
Dim MyType as System.Type = A.gettype ("Class1") ' Gets the Type of the Class1
Dim obj as Object = activator.createinstance (MyType) ' obtains an instance of Class1

3.class1.vb Original Document

The following are the referenced contents:
Public Class Class1class Class1
Public I as Integer
End Class



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.