Creating class objects using reflection principles in C #

Source: Internet
Author: User

Case:

There is now a Device.dll file with a namespace of device, containing two classes of Device1 and Device2, and now the Device1 and Device2 classes are created through the reflection principle, with the following specific statements:

1, the first need to add reference using System.Reflection;

2. Create Device1

Assembly Asmdevice = Assembly.Load ("Device");//Loading namespaces

Type device1type= asmdevice.gettype ("Device.device1");//Gets the class under the namespace

Object ASSCLAS1 = Activator.CreateInstance (Device1type);//Instantiate the specified class that is reflected back

Device1 device1= (Device1) Assclas;

3. Create Device2

Assembly asmdevice= assembly.load ("Device");//Loading namespaces

Type device2type= asmdevice.gettype ("Device.device2");//Gets the class under the namespace

Object ASSCLAS2 = Activator.CreateInstance (Device2type);//Instantiate the specified class that is reflected back

Device2 device1= (DEVICE2) Assclas;

Description

Assembly.Load ("filename of the. dll assembly file");

Asmdevice.gettype ("Namespace of assembly, class name");

The above four lines of code creating Device1 are equivalent to the following line:

Device1 device1= (Device1) assembly.load ("Device"). GetType ("Device.device1"). CreateInstance (Device1);

Extension Description:

If both Device1 and Device2 inherit from the interface idevice, you can also have the following implementations:

IDevice device= (IDevice) assembly.load ("Device"). GetType ("Device.device1"). CreateInstance (Device1);

Or

IDevice device= (IDevice) assembly.load ("Device"). GetType ("Device.device2"). CreateInstance (DEVICE2);

Creating class objects using reflection principles in C #

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.