解析继承基控制器并实现特定类的泛型控制器

本文关键字:控制器 泛型 继承 实现 | 更新日期: 2023-09-27 18:25:20

我正在尝试解析一个继承基控制器并实现特定类的通用控制器。我的措辞——对"事物"的命名——并不是最好的,所以我将尝试用代码来解释它。

public class BaseObject
{
}
public class TestObject : BaseObject
{
}
public class BaseController<T> : Controller
{
}
public class TestObjectController : BaseController<TestObject>
{
    public ActionResult Index()
    {
        return View(new TestObject());
    }
}
 public static MvcHtmlString RenderObj<TModel, TProperty>(this HtmlHelper<TModel> helper,
        Expression<Func<TModel, TProperty>> expression)
{
    var name = ExpressionHelper.GetExpressionText(expression);
    var metaData = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
    var baseObject = metaData.Model as BaseObject; //In this case baseObject is TestObject
    var type = baseObject.GetType();
    var assembly = type.Assembly;
    var t = assembly.GetTypes(); //Here I want to find TestObjectController<TestObject>
}

解析继承基控制器并实现特定类的泛型控制器

简单的控制台应用程序,它没有经过充分的测试,但应该会让您走上正轨。我把错误检查和进一步过滤留给你:

static void Main(string[] args)
{
    // obviously you already have this
    BaseObject obj = new TestObject();
    // you know this
    var myType = obj.GetType();
    // you know the type of the base class
    var baseControllerType = typeof(BaseController<>);
    // make the type generic using your model type
    baseControllerType = baseControllerType.MakeGenericType(myType);
    // the baseControllerType is now Generic BaseController<TestObject>
    // reference all types in a variable for a 'cleaner' linq query expression
    var allTypes = Assembly.GetEntryAssembly().GetTypes();
    // get all types that are a sub class of BaseController<TestObject>
    var daController = (from type in allTypes
                        where type.IsSubclassOf(baseControllerType)
                        select type).FirstOrDefault();
    // optionally create an instance.
    var instance = Activator.CreateInstance(daController);
}
public class BaseObject
{
}
public class TestObject : BaseObject
{
}
public class BaseController<T>
{
}
public class TestObjectController : BaseController<TestObject>
{
}