当前位置:编程学习 > C#/ASP.NET >>

Metadata and Reflection in .NET

答案:begin:
Posted by scott on 2004年11月10日

The .NET platform depends on metadata at design time, compile time, and execution time. This article will cover some theory of metadata, and demonstrate how to examine metadata at runtime using reflection against ASP.NET web controls.
Metadata is the life blood of the .NET platform. Many of the features we use everyday during design time, during compile time, and during execution time, rely on the presence of metadata. Metadata allows an assembly, and the types inside an assembly, to be self-describing. In this article, we will discuss metadata and look at some of types and methods used to programmatically inspect and consume metadata.

Metadata – Some History
Metadata is not new in software development. In fact, many of .NETs predecessors used metadata. COM+ for instance, kept metadata in type libraries, in the registry, and in the COM+ catalog. This metadata could describe if a component required a database transaction or if the component should participate in object pooling. However, since the COM runtime kept metadata in various locations, irregularities could occur. Also, the metadata could not fully describe a type, and was not extensible.

A compiler for the common language runtime (CLR) will generate metadata during compilation and store the metadata (in a binary format) directly into assemblies and modules to avoid irregularities. The CLR also allows metadata extensibility, meaning if you want to add custom metadata to a type or an assembly, there are mechanisms for doing so.

Metadata in .NET cannot be underestimated. Metadata allows us to write a component in C# and let another application use the metadata from Visual Basic .NET. The metadata description of a type allows the runtime to layout an object in memory, to enforce security and type safety, and ensure version compatibilities.

Metadata & Reflection
Reflection is the ability to read metadata at runtime. Using reflection, it is possible to uncover the methods, properties, and events of a type, and to invoke them dynamically. Reflection also allows us to create new types at runtime, but in the upcoming example we will be reading and invoking only.

Reflection generally begins with a call to a method present on every object in the .NET framework: GetType. The GetType method is a member of the System.Object class, and the method returns an instance of System.Type. System.Type is the primary gateway to metadata. System.Type is actually derived from another important class for reflection: the MemeberInfo class from the System.Reflection namespace. MemberInfo is a base class for many other classes who describe the properties and methods of an object, including FieldInfo, MethodInfo, ConstructorInfo, ParameterInfo, and EventInfo among others. As you might suspect from thier names, you can use these classes to inspect different aspects of an object at runtime.

Metadata : An Example
In the web form shown below we will allow the user to inspect and set any property of a web control using reflection techniques. We have a Panel control on the bottom of the form filled with an assortment of controls (in this case, a TextBox, a Button, a HyperLink, and a Label, although if you download the code you can drag any controls into the panel and watch the example work).



When the page initially loads we will loop through the Controls collection of the Panel to see what controls are available. We can then display the available controls in the ListBox and allow the user to select a control. The code to load the ListBox is shown below.


private void Page_Load(object sender, System.EventArgs e)
{
if(!Page.IsPostBack)
{
PopulateControlList();
}
}

private void PopulateControlList()
{
foreach(Control c in Panel1.Controls)
{
if(c is WebControl)
{
controlList.Items.Add(new ListItem(c.ID, c.ID));
}
}
}


You can see we test each control in the Panel to see if it derives from WebControl with the ‘is‘ keyword. If the control is a type of WebControl, we add the ID of the control to the list. The user can then select a control from the list with the mouse. We have set the list control’s AutoPostBack property to true so it will fire the SelectedIndexChanged event when this happens. During the event we want to populate a DropDownList control with the properties available on the selected object. The code to perform this task is shown next.


private void controlList_SelectedIndexChanged(object sender, System.EventArgs e)
{
PopulatePropertyList();
}

private void PopulatePropertyList()
{
propertyList.Items.Clear();
valueText.Text = String.Empty;
WebControl control = FindSelectedPanelControl();

if(control != null)
{
Type type = control.GetType();

PropertyInfo[] properties = type.GetProperties();

foreach(PropertyInfo property in properties)
{
propertyList.Items.Add(new ListItem(property.Name));
}

GetPropertyValue();
}
}

private WebControl FindSelectedPanelControl()
{
WebControl result = null;

string controlID = controlList.SelectedItem.Text;

result = Panel1.FindControl(controlID) as WebControl;

return result;
}


The first step in PopulatePropertyList is to obtain a reference to the control the user selected. We do this step in FindSelectedPanelControl by asking the list for the selected item’s Text property (which is the ID of the control). We can then pass this ID to the FindControl method to retrieve the control reference.

With the reference in hand we call GetType to obtain a Type reference. The Type class, as we mentioned before, is the gateway to obtaining metadata at runtime. By invoking the GetProperties method we obtain an array of PropertyInfo objects. The PropertyInfo class gives each object in the array a Name property, and we can populate the DropDownList with the name.

The DropDownList also has AutoPostBack set to true to let us catch the SelectedIndexChange event when the user selects a property to inspect. When this event fires we want to obtain the value of the property the user selected, as shown in the event handling code below.


private void GetPropertyValue()
{
WebControl control = FindSelectedPanelControl();
Type type = control.GetType();

string propertyName = propertyList.SelectedItem.Text;
BindingFlags flags = BindingFlags.GetProperty;
Binder binder = null;
object[] args = null;

object result = type.InvokeMember(
propertyName,
flags,
binder,
control,
args
);

valueText.Text = result.ToString();
}


Once again we will obtain a reference to the selected control using FindSelectedPanelControl, then use that control reference to obtain a Type reference for the control. Next, we need to setup parameters to invoke the property by name using InvokeMember. The InvokeMember allows us to execute methods by name (and a property is a special type of method).

The first parameter to InvokeMember is the name of the member to call. For example, “ImageUrl” is the name of a HyperLink control member. The second parameter is a BindingFlags enumeration. BindingFlags tell InvokeMember how to look for the named member. By passing BindingFlags.GetProperty we are telling InvokeMember to look for “ImageUrl” as a “get” property method, as opposed to a “set” property method (because in the runtime, get_ImageUrl and set_ImageUrl are the two methods behind the ImageUrl property).

The binder parameter for InvokeMemb

上一个:学习笔记《.NET框架程序设计(修订版)》--第三章 共享程序集 (2)
下一个:在.net执行sql脚本的简单实现

CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,