我正在尝试解析一个继承基本控制器并实现特定类的通用控制器。 我对“事物”命名的措辞并不是最好的,所以我将尝试用代码解释它。
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>
}
答案 0 :(得分:1)
简单的控制台应用程序,没有经过彻底的测试,但应该让你走在正确的轨道上。 我留下错误检查并进一步向下过滤给你:
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>
{
}