【问题标题】:Get Usercontrol which inherits Type X using reflection使用反射获取继承 Type X 的 Usercontrol
【发布时间】:2012-08-28 11:07:45
【问题描述】:

给定 Web 应用程序中的这个用户控件 ascx:

<%@ Control Language="C#" Inherits="TypeX" Codebehind="TypeX.ascx.cs" %>

我开始时是否可以使用反射来获取用户控件:

Type targetType = typeof(TypeX);
... now what? to code to get the usercontrol

我试过用:

assembly.GetTypes().Where(t => t.IsSubclassOf(targetType))

但这并没有给出任何结果。

任何帮助表示赞赏

额外信息:

代码隐藏(简化)是:

 public partial class TypeX : UserControlBase
{
}

//we use this control:
<%@ Control Language="C#" Inherits="Loadcontrol " Codebehind="Loadcontrol .ascx.cs" %>
//with this codebehind
 public partial class Loadcontrol 
{
    OnPrerender()
    {
        string controlToLoad = "TypeX";
        //what to do here
    }

}

我希望现在更清楚了

更新:我制作了一个示例 web 应用程序来显示问题。 下载地址:WebApplication1.zip 或使用:Download mirror

【问题讨论】:

    标签: c# asp.net reflection


    【解决方案1】:
    Type targetType = typeof(TypeX);
    var control = Page.LoadControl(targetType, null);
    

    您需要在页面中使用此代码。

    【讨论】:

    • 问题是:我是不在页面中的 TypeX 的基类。所以我不能在那里使用 LoadControl... 我可以吗?
    • 我看到您在用户控件中。您可以使用 Page 属性中的 LoadControl
    • 当我这样做时,我没有得到与以下相同的结果:Page.LoadControl(".ascx")。
    • 当我使用 Page.LoadControl(targetType, null);我得到了一个带有代码隐藏类型的控件,所以没有 ascx 中标记的所有知识。当我使用 Page.LoadControl(".ascx") 我从 ascx 中的标记中获得所有控件的类型
    • 你如何区分结果?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-08
    • 1970-01-01
    • 2014-09-06
    • 2011-07-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多