IAttributeAccessor 接口

定义

定义由 ASP.NET 服务器控件用来对服务器控件的开始标记中声明的任何特性提供编程访问的方法。

public interface IAttributeAccessor
派生

示例

// The following class creates a custom ASP.NET server control that implements
// the IAttributeAccessor interface. It creates a MyTextBox class that contains
// Width and Text properties that get and set their values from view state.
// Pages that use this control create an instance of this control and set the
// Width property using the IAttributeAccessor.SetAttribute method. 
// The page then displays the values of the Text and Width properties 
// using the IAttributeAccessor.GetAttribute method.
// When compiled, this assembly is named MyAttributeAccessor.
using System;
using System.Web;
using System.Web.UI;
using System.Security.Permissions;

namespace AttributeAccessor
{
   [AspNetHostingPermission(SecurityAction.Demand, 
      Level=AspNetHostingPermissionLevel.Minimal)]
   public sealed class MyTextBox : Control, IAttributeAccessor
   {
      // Declare the Width property.
      public String Width
      {
         get
         {
            return (String)ViewState["Width"];
         }
         set
         {
            ViewState["Width"] = value;
         }
      }

      // Declare the Text property.
      public String Text
      {
         get
         {
            return (String)ViewState["Text"];
         }
         set
         {
            ViewState["Text"] = value;
         }
      }
      // Implement the SetAttribute method for the control. When
      // this method is called from a page, the control's properties
      // are set to values defined in the page.
      public void SetAttribute(String name, String value1)
      {
         ViewState[name] = value1;
      }

      // Implement the GetAttribute method for the control. When
      // this method is called from a page, the values for the control's
      // properties can be displayed in the page.
      public String GetAttribute(String name)
      {
         return (String)ViewState[name];
      }

      protected override void Render(HtmlTextWriter output)
      {
         output.Write("<input type=text id= " + this.UniqueID);
         output.Write(" Value='" + this.Text);
         output.Write("' Size=" + this.Width + ">");
      }
   }
}

注解

如果创作继承自 、 HtmlControlListItem 类的WebControl自定义服务器控件,则 .NET Framework 会自动提供对属性的编程访问,因为其中每个类都实现 IAttributeAccessor 接口。

如果创作的自定义服务器控件不继承自这些类之一,并计划允许以编程方式访问与控件的强类型属性不对应的属性,请确保实现 IAttributeAccessor 接口。

方法

GetAttribute(String)

当由某个类实现时,检索服务器控件中指定的特性属性。

SetAttribute(String, String)

当由类实现时,指定要分配给 ASP.NET 服务器控件的特性及其值。

适用于

产品 版本
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1

另请参阅