- 热门文章:
- · 在.net执行sql脚本的简单实现
- · .Net下WebMethod属性
- · .NET客户端应用程序:.NET应用程序更新组件(6)
- · .NET客户端应用程序:.NET应用程序更新组件(5)
- · 创建分布式应用程序学习心得
- · 基于组件的.NET软件开发(1)
- · .net关于企业Excel报表的生成
- · 使用 Visual C# .NET 在 ADO.NET 中以编程方式构建连接字符串
- · 让用户通过宏和插件向您的 .NET 应用程序添加功能
- · Visual Basic.NET和GDI+共创图标编辑器
- · Visual Basic .NET 中动态加载类 (三)
- · Visual Basic .NET 中动态加载类 (二)
Metadata and Reflection in .NET
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 InvokeMember is a parameter we do not use, so we pass null. A binder is useful in rare circumstances where we need explicit control over how the reflection code selects a member and converts arguments. By passing a null value we are letting reflection use the default binder to perform the member lookup and argument passing.
The fourth parameter to InvokeMember is the target object instance. This is the object the runtime will try to invoke the member upon, so we pass the reference to the selected control. Finally, the last parameter is a parameter for any arguments to pass to the member. Since fetching a property does not require any parameters we can pass a null value.
InvokeMember returns an object which is the return value of the member we called (if we were to InvokeMember on a member returning void, InvokeMember returns a null value). If we InvokeMember on ImageUrl we will get back a string, we will take this string and display it in the valueText TextBox control.
If the user modifies the valueText control and clicks the “Set Property” button, we want to set the selected property with the value. The event handler for the button is shown next.
private void SetPropertyValue()
{
WebControl control = FindSelectedPanelControl();
Type type = control.GetType();
string propertyName = propertyList.SelectedItem.Text;
BindingFlags flags = BindingFlags.SetProperty;
Binder binder = null;
object arg = CoherceStringToPropertyType(control, propertyName, valueText.Text);
object[] args = { arg };
type.InvokeMember(
propertyName,
flags,
binder,
control,
args
);
}
Once again we retrieve a reference to the selected control, and a reference to the runtime type representation of the control with GetType. This time we setup the InvokeMember parameters to perform a “set property” operation. Notice the BindingFlags have chanced to BindingFlags.SetProperty. We also now have to pass an argument array, with the one argument being the value the user has typed into the textbox. We can’t just pass this string in the argument array, however, because not all of the properties take a string argument. The AutoPostBack property, for instance, takes a boolean parameter. To force the parameter into the correct type we call the method below.
private object CoherceStringToPropertyType(WebControl control,
string propertyName,
string value)
{
object result = null;
Type type = control.GetType();
PropertyInfo p = type.GetProperty(propertyName);
Type propertyType = p.PropertyType;
TypeConverter converter = TypeDescriptor.GetConverter(propertyType);
result = converter.ConvertFrom(value);
return result;
}
The method above uses a TypeConverter object. A TypeConverter is useful for converting types from a textual representation back to their original type (for the AutoPostBack property, we would convert a string to a bool). Notice we can retrieve the TypeConverter for a given property by asking the TypeDescriptor class to give us a TypeConverter. This allows us to avoid writing a large amount of code, perhaps with a switch statement, that would examine the property type to determine what kind of type we need (string, bool, int, or some class we’ve never heard of). Instead, the metadata of the type allows it to be self-describing and give us an object that can perform the specific conversion for us.
This article only touches upon some of the basic features of metadata and reflection. Here are some additional resources for more information.
Displaying Metadata in .NET EXEs with MetaViewer
Dynamically Bind Your Data Layer to Stored Procedures and SQL Commands Using .NET Metadata and Reflection
Use Reflection to Discover and Assess the Most Common Types in the .NET Framework
How Microsoft Uses Reflection
Download the code for this article: ReflectIt.zip
-- by K. Scott Allen
下一篇:在.net执行sql脚本的简单实现 >>
相关文章:
- · Visual Basic .NET 中动态加载类(一)
- · 我的.Net下应用程序发布问题的简易解决方案
- · 关于自定义事件的一点体会
- · .net 中的事务总结
- · .net中一些所封装的类
- · .Net 下对SqlServer2000中的存储过程的调用
- · .Net 下对SqlServer2000中的存储过程的调用
- · .NET组件和COM组件之间的相互操作
- · 权限管理工具的使用方法
- · .net关于企业Excel报表的生成
- · .NET Test Driven Development
- · 使用 Visual C# .NET 向 Microsoft Excel 2002 传输 XML 数据
- · Remoting编程知识二
- · Remoting编程知识一
- · 在.net中轻松掌握Windows窗体间的数据交互
- · .NET里面的Interop太烂了
- · .NET中的设计模式五:观察者模式
- · .NET Framework 2.0 beta 新特性
- · 把.NET程序部署到没有安装.NET Framwork的机器上
- · 对使用net程序架构开发的一点点儿
- · 在.NET下获取硬盘序列号的问题
- · 在.net中Oracle日期类型的处理
- · 由C++转向C#:我们需要注意哪些方面的变化?
- · 如何保护我们的 .NET 程序集?
- · 初级:.net框架下的MD5
- · .net下软件的自动升级--上传
- · 针对 .NET 框架的安全编码指南
- · .NET框架类命名空间
- · .Net框架程序设计(一)----进阶
- · .NET中的设计模式二:单件模式
- · .Net的注册表操作
- · [GDI+] ColorMatrix 彩色矩阵
- · 在.NET中实现彩色光标,动画光标和自定义光标
- · .Net框架下的XSLT转换技术简介
- · NET Framework 工具
- · 充分利用 .NET 框架的 PropertyGrid 控件
- · 把.NET程序部署到没有安装.NET Framwork的机器上
- · ADO连接数据库字符串大全
