C # obtain a subclass of a class from reflection and dynamically create an object based on the Type name

Source: Internet
Author: User

Sometimes, in order to quickly batch process subclasses that have implemented a base class or an interface, you need to obtain their class Type through reflection, and then pass

Activator.CreateInstance(objType);

Or

Assembly.Load(path).CreateInstance(typeName);

Or

Assembly.LoadFile(filePath).CreateInstance(typeName);

Create an object instance.

The following is a simple example:
1. obtain all types in the current Assembly;
2. Determine whether a type is inherited or not;
3. dynamically create an object based on the Type name.

I have another question, but I don't know who can answer it:
1. How to determine whether a class has implemented an interface? Currently, only one new object can be created first, and then use is to determine whether a class has implemented an interface.

Using System; using System. collections. generic; using System. text; using System. reflection; using System. diagnostics; namespace com. hetaoos {class Test {public Test () {var types = Assembly. getExecutingAssembly (). getTypes (); var baseType = typeof (BaseProcessor); List <BaseProcessor> processors = new List <BaseProcessor> (); foreach (var t in types) {var tmp = t. baseType; while (tmp! = Null) {if (tmp = baseType) {BaseProcessor obj = MethodMaker. CreateObject (t. FullName) as BaseProcessor; if (obj! = Null) {processors. add (obj);} break;} else {tmp = tmp. baseType ;}} Debug. print ("Processor Count: {0}", processors. count); foreach (var p in processors) {Debug. print ("{0} \ t: {1}", p, p. calc (2, 5) ;}} public class MethodMaker {/// <summary> // create an object (current Assembly) /// </summary> /// <param name = "typeName"> type name </param> /// <returns> created object, return null for failure </returns> public static object CreateObject (string typeName) {object obj = null; try {Type objType = Type. getType (typeName, true); obj = Activator. createInstance (objType);} catch (Exception ex) {Debug. write (ex);} return obj;} // <summary> // create an object (external Assembly) /// </summary> /// <param name = "path"> </param> /// <param name = "typeName"> type name </param>/ // <returns> created object, return null for failure </returns> public static object CreateObject (string path, string typeName) {object obj = null; try {obj = Assembly. load (path ). createInstance (typeName);} catch (Exception ex) {Debug. write (ex);} return obj ;}} public abstract class BaseProcessor {public abstract int Calc (int a, int B);} public class Adder: baseProcessor {public override int Calc (int a, int B) {return a + B;} public class Multiplier: BaseProcessor {public override int Calc (int a, int B) {return a * B ;}}}

Output result:

Processor Count:2com.hetaoos.Adder:7com.hetaoos.Multiplier:10

PS:
Methods used to determine whether a class inherits from an interface or class:

        public static bool IsParent(Type test, Type parent)        {            if (test == null || parent == null || test == parent || test.BaseType == null)            {                return false;            }            if (parent.IsInterface)            {                foreach (var t in test.GetInterfaces())                {                    if (t == parent)                    {                        return true;                    }                }            }            else            {                do                {                    if (test.BaseType == parent)                    {                        return true;                    }                    test = test.BaseType;                } while (test != null);            }            return false;        }

 

 

Reprinted from: http://blog.hetaoos.com/archives/40

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.