首页 > 编程 > .NET > 正文

Metadata and Reflection in .NET

2024-07-10 12:59:16
字体:
来源:转载
供稿:网友
  • 本文来源于网页设计爱好者web开发社区http://www.html.org.cn收集整理,欢迎访问。
  • 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 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

    发表评论 共有条评论
    用户名: 密码:
    验证码: 匿名发表