简体   繁体   中英

Casting generic parameter to subclass

Please look at the code bellow:

public class BaseClass
{
}

public class SubClass : BaseClass
{
}

public class QueryClass
{
    public TBaseClass[] QueryBase<TBaseClass>() where TBaseClass : BaseClass
    {
        throw new NotImplementedException();
    }

    public TSubClass[] QuerySub<TSubClass>() where TSubClass : SubClass
    {
        throw new NotImplementedException();
    }

    public TClass[] Query<TClass>() where TClass : BaseClass
    {
        if (typeof(TClass).IsSubclassOf(typeof(SubClass)))
        {
            return QuerySub<TClass>(); // there is error The type 'TClass' must be convertible to SubClass
        }

        return QueryBase<TClass>();
    }
}

The question is how to implement Query method. If it is possible..

What you are trying to do is doing something like this:

public class Animal { }
public class Dog : Animal { }

public void HandleAnimal<T>() where T : Animal
{

}
public void HandleDog<T>() where T : Dog
{

}

When you have a reference to Animal in this case, there is no way of knowing what typeof animal it is. Even if the method returns true, in the context of your code it is still always an Animal and you can't handle a dog when all you know is that the type is an animal . If you were handling instances of objects inside the method you could potentially start casting or instansiating the subclass if you know that it is a subclass and then pass that through.

Ended up with reflection.

        if (typeof(TClass).IsSubclassOf(typeof(SubClass)))
        {
            var method = typeof(QueryClass).GetMethod("QuerySub").MakeGenericMethod(typeof (TClass));

            return (TClass[]) method.Invoke(this, new object[0]);
        }

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