ASP.Net应用程序每个页面中使用的控件数?
有没有办法找出ASP.Net应用程序每个页面中使用的控件数?ASP.Net应用程序每个页面中使用的控件数?,asp.net,Asp.net,有没有办法找出ASP.Net应用程序每个页面中使用的控件数? 请帮忙你为什么需要它?首先定义控件,从System.Web.UI.Control派生的所有内容 您可以编写一个递归扩展方法,该方法将延迟返回所有控件,因此很简单: protected void Page_PreRender(object sender, EventArgs e) { var allControls = this.GetControlsRecursively().ToList(); } 以下是一个可能的实现:
请帮忙你为什么需要它?首先定义控件,从
System.Web.UI.Control
派生的所有内容
您可以编写一个递归扩展方法,该方法将延迟返回所有控件,因此很简单:
protected void Page_PreRender(object sender, EventArgs e)
{
var allControls = this.GetControlsRecursively().ToList();
}
以下是一个可能的实现:
public static class ControlExtensions
{
public static IEnumerable<Control> GetControlsRecursively(this Control parent)
{
foreach (Control c in parent.Controls)
{
yield return c;
if (c.HasControls())
{
foreach (Control control in c.GetControlsRecursively())
{
yield return control;
}
}
}
}
}
公共静态类控制扩展
{
公共静态IEnumerable GetControlsRecursive(此控件父控件)
{
foreach(父控件中的控件c)
{
收益率c;
if(c.HasControls())
{
foreach(c.getControlsRecursive()中的控件)
{
收益率控制;
}
}
}
}
}
您为什么需要它?首先定义控件,从System.Web.UI.Control
派生的所有内容?次要问题:使用-而不是c.controls.Count>0
faster@HansKesting:谢谢,请进行相应的编辑。但我认为性能并不是我们应该选择HasControls
的原因。递归触摸控件
属性将导致加载ViewState(如果尚未为所有控件加载),这可能会导致副作用。