简体   繁体   中英

Check if a class exists within the current .NET assembly

I would like to be able to verify that a class exists within the current assembly before attempting to create it using Activator.CreateInstance .

Currently I build a fully qualified class name based on some meta-data retrieved from a 3rd party application I am extending. This class name is then created using Activator.CreateInstance and cast to a common base class.

I'm looking for something along the lines of:

string className = "MyNamespace." + "some_arbitary_class_name";
if (Assembly.ClassExists(className))
{
     // Create the class.
}

Currently I have this:

 string class_name = "MyNamespace.BaseClassImpl_" + meta_data;
 MyBaseClass baseClass = null;
 try
 {
     baseClass = (BaseClass)Activator.CreateInstance(null, class_name);
 }
 catch (Exception e) { }
 // If base class in null, failed.

I know that I need to use System.Reflection to inspect the current assembly but I'm at a loss of the exact methods I need to use.

So my question is twofold:

  1. Could someone please direct me to the .NET api I need to use to accomplish this?
  2. Is it good practice to verify that a class exists before creating it? Or should I just let the try-catch block handle it?

You could do an Assembly.GetType ("assembly") and see if that returns null, there is also another overload that allows you to specify a parameter of whether to throw if if the type doesnt exist.

If you can I'd say its probably best to avoid the exception, it will probably make your code harder to read at the very least.

Daniel Powells answer was exactly what I needed to get this done.

In the end, this a rough translation of the code I used to achieve what I needed to do:

class MyBaseClass
{   }

class MyBaseClass_impl : MyBaseClass
{   }

public MyBaseClass CreateFromMetaData(string metaData)
{
    string className = "MyNamespace.MyBaseClass_" + metaData;
    Type t = System.Reflection.Assembly.GetExecutingAssembly().GetType(className, false);
    if (t != null)
    {
        return (MyBaseClass)Activator.CreateInstance(t);
    }

    return null;
}

Following this, using "impl" as the parameter for CreateFromMetaData would return a new MyBassClass_impl object, while any other string would return null.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM