简体   繁体   中英

How to get the type of derived class at base class without generics?

My base class use reflection on derived classes to provide some functionality to them. Currently I do it this way:

abstract class BaseClass<T>
{
    string GetClassString()
    {
        // Iterate through derived class, and play with it's properties
        // So I need to know the type of derived class (here T).
        return result;
    }

    static bool TryParse(string classString, out T result)
    {
        // I should declare a variable as T and return it
    }
}

Can I do this without generics ?

Edit:

Sorry, you want the type parameter (ie typeof(T) ). In that case you still use this.GetType() but you add .GetGenericArguments()[0] after.

Try parse: You need to create a new instance of a type you don't know

There are two ways: First, without changing the rest, with the Activator class and the following code:

result = (T) Activator.CreateInstance(typeof(T))

( MSDN ).

Then, you could add a "new" constraint to your type:

MyClass<T> where T : new() {...}
result = new T();

Both samples require parameter less constructors. If you want to pass parameters, then you need to go deeper inside System.Reflection, get the list of constructors and call the one you want. A factory pattern may also do the job.

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