mardi 4 août 2015

How to check if object inherits from a generic base class without knowing type of typeparam

I have the following construct for classes:

public class Request : BaseRequest, IRequestFromResponse
{
}

which defines a Request-object to be posted via html form.

The Model, where the Request lives in build up like:

public class Response : BaseRequestWrapperResponse<Request>
{
}

while the BaseWrapper is build:

public abstract class BaseRequestWrapperResponse<TRequest> where TRequest : IRequestFromResponse
{
    public TRequest Request { get; set; }
}

IRequestFromResponse is just an empty marker-interface.

I try to cast the object at runtime, so I have access to the Request-property of BaseRequestWrapperResponse.

All I have so far is:

var model = ((ViewContext) context).ViewData.Model;

if (model.GetType().IsSubclassOf(typeof (BaseRequestWrapperResponse<IRequestFromResponse>)))
// if (model.GetType().BaseClass.IsAssignableFrom(typeof (BaseRequestWrapperResponse<IRequestFromResponse>)))
// if (model.GetType().IsSubclassOf(typeof (BaseRequestWrapperResponse<>)))
// if (model.GetType().BaseClass.IsAssignableFrom(typeof (BaseRequestWrapperResponse<>)))
{
    model = ((BaseRequestWrapperResponse<IRequestFromResponse>) model).Request;
}

I'm not able to get a check which indicates that model is some sort of BaseRequestWrapperResponse. The cast would then be my next problem.





Aucun commentaire:

Enregistrer un commentaire