C # Basic Series--attribute features use

Source: Internet
Author: User

Preface: The previous C # Basic series-Reflection notes summarize the underlying usage of reflection, this chapter we look at another basic technology of C #-features.

1, what is the characteristics: on the understanding of the blogger, the characteristics of the class name, attributes, methods and so on add a tag, so that these classes, properties, methods, etc. have some unified characteristics, so as to achieve some special needs. For example: The method of abnormal capture, you are still in some of the possible anomalies (such as database operations, file operations, etc.) often use Try...catch. This time if the use of features, you can greatly reduce the use of try...catch inside the method. You just need to define an attribute class Exceptionexattribute that specifically catches the exception, and then give the feature class some special handling, such as adding an AOP intercept to it (there are many ways to block AOP, and there are many similar articles in the garden that are interesting to search for). This method has the ability to automatically catch exceptions by adding a [Exceptionex] attribute tag to the name of the method that may appear the exception. Or add the official definition:

Features provide powerful methods for associating metadata or declarative information with code (assemblies, types, methods, properties, and so on). attribute is associated with a program entity, you can use a technical query feature called Reflection at run time.

Attributes have the following properties:

  • attribute to add metadata to your program.  metadata is information about The types defined in a programs. The "data-guid=" 01e24c05eb8a815d9d031ae958a894ae "> metadata is information about the types defined in your program.   all. NET assemblies contain a specified set of metadata That describes the types and type members defined in the assembly.   You can add a custom attribute to specify any additional information you want.  

  • You can apply one or more attributes to an entire assembly, a module, or a smaller program element, such as classes and attributes.

  • Attributes can accept parameters in the same way as methods and properties.

  • A program can use reflection to check its own metadata or metadata within other programs.

(above from MSDN)

2, why need features: This has been briefly described above, features can greatly reduce the unified requirements of the code volume. Others do not say, at least it can make our code look more atmospheric dot ~ ~

3, the use of features: Bo Master this time or intends to introduce the characteristics of the general use of three. Of course, these kinds of methods are the original used by bloggers, may not be the best example of the scene, but also a more typical use of the characteristics of it.

(1) The use of attributes above the class:

The reason for this is that the most recent BS project that bloggers have done is just used, and the use of the scene is more typical. Let's start with the following scenario: there is a requirement for a recent project, and the BS interface requires a drag-and-drop function. Such as

When you drag the left 3 div to the right, each div has its own unique properties, such as when the 2-door is dragged over, to display the following properties:

1 and 3 Doors may have different properties when dragged over.

Design ideas: Each div corresponds to the model, each model has its own unique attributes, and then the attributes are added to the attribute Display property name and default value, and the interface should be rendered HTML tags.

Implementation code:

Let's start with a custom attribute class:

public class Detailattribute:attribute    {public        string Attrname {set; get;}        public string Html {set; get;}        public string DefaultValue {set; get;}        public string DataSource {set; get;}    }

The corresponding model:

   public class Factory {[Detail (attrname= "width", html= "<input type= ' text '/>", defaultvalue= "", Datasour "        Ce=null)] public string Width {set; get;} [Detail (attrname = "height", Html = "<input type= ' text '/>", defaultvalue = "", DataSource = null)] public stri        ng Height {set; get;}  [Detail (Attrname = "state", Html = "<select></select>", DefaultValue = null, DataSource = "Select Text,value from        Status ")] public string Status {set; get;} [Detail (attrname = "Tag Value", Html = "<input type= ' text '/>", defaultvalue = "", DataSource = null)] public stri    ng Tag {set; get;} } public class Factorydetail {[Detail (attrname = "width", Html = "<input type= ' text '/>", DefaultValue =        "", DataSource = null)] public string Width {set; get;} [Detail (attrname = "height", Html = "<input type= ' text '/>", defaultvalue = "", DataSource = null)] public stri ng Height {set; get; } [Detail (attrname = "state", Html = "<select></select>", DefaultValue = null, DataSource = "Select text,        Value from status ')] public string Status {set; get;} [Detail (attrname = "Tag Value", Html = "<input type= ' text '/>", defaultvalue = "", DataSource = null)] public stri        ng Tag {set; get;}  [Detail (attrname = "description", Html = "<input type= ' text '/>", defaultvalue = "", DataSource = null)] public string    Desc {set; get;} }

Then, at the end of the drag-and-drop event at the interface, send an AJAX request via JS to get the HTML that the interface renders:

$ (". Jq-draggable-outcontainer"). Draggable ({helper: "clone", Scroll:true, Drag:function (event, UI)        {//debugger;    }    });            $ ("#content"). Droppable ({drop:function (event, UI) {//debugger; if (Ui.draggable[0].classname.indexof ("Jq-draggable-outcontainer") > 0) {var text = Ui.draggable[0].inn                Ertext.trim (); $ (this). Append (' <div class= ' window Jq-draggable-incontainer "onclick=" Getpropertiesbytype (\ ' 1\ ', this) "style=" Position:absolute;left: ' + (event.clientx-20) + ' px;top: ' + (event.clienty-20) + ' px ' id= "window ' + iIndex + '" ><stro                Ng> ' + text + ' </strong></div> ');                $ ("#content2"). HTML ("");                Cur_selector = $ ("#window" +iindex); $. Ewin.ajaxpost ("/home/getmodelbytype", {strtype: "Factory"}, function (data, status) {var element = $ . Parsejson (data.                    Json); var arrprop = Element.elEment.property; 0. construct html var strhtml = "<div style= ' Float:right;padding-top:0px;width:300px;height:auto; '                    ><table cellpadding= ' 5 ' border= ' 1 ' > ";                    1. Spelling HTML Construction Properties strHTML + = "</table></div>";                $ ("#content2"). Append (strhtml);                }, function () {}, NULL);            iindex++; }        }    });

The corresponding C # method:

Public Jsonresult Getmodelbytype (string strtype) {
The Strtype pass is factory or factorydetail var assembly = assembly.load ("Ewin.Client.Web");//parameter is the name of the Assembly VAR Otype = assembly. GetType ("Ewin.Client.Web.Controllers." + strtype);
Get all the properties of the class var lstproperties = Otype.getproperties (); foreach (Var oproperty in lstproperties) {
Get the attribute class collection for each attribute ilist<customattributedata> lstattr = Oproperty.getcustomattributesdata (); foreach (Var oattr in lstattr) {
Get the full name of each attribute class Console.WriteLine ("Name of the attribute class" + oAttr.AttributeType.FullName); Console.WriteLine ("Attribute class members are as follows:");
Get all the parameters of the attribute class var lstattrargu = oattr.namedarguments; foreach (Var oattraru in Lstattrargu) {
Take the key value pair Console.WriteLine (oattraru.membername + "=" + OAttrAru.TypedValue.Value) for each attribute class parameter; }//console.writeline (oattr.attributetype+ "--" +oattr.namedarguments); }} return Json (new {}, Jsonrequestbehavior.allowget); }

The Getmodelbytype method results in a simple construction and then returns the property's key-value pair to the JS method, which is then appended to the interface by JS. This allows the design of this small function to be accomplished quickly by combining features and reflections.

(2) The method of the class uses the above attribute:

There is a lot of this usage in the. Net framework, if you use the filter filters in MVC:

public class Superlogstat:actionfilterattribute {//module name private Enummodulename moduleenum = Enummodule        Name.moduleother; Function name private string functionname = String.        Empty; User ID private String userId = String.                Empty;        public string Version {get {return configurationmanager.appsettings["uploatstatversion"];}            } public enummodulename Moduleenum {get {return this.moduleenum;}        set {this.moduleenum = value;}            } public string FunctionName {get {return this.functionname;}        set {this.functionname = value;}        }//Both methods are virtual methods of the parent class, one before return View () executed, one after the execution////Summary://Called by the MVC framework before executing the action method.        Parameters://Filtercontext://filter context.  public override void OnActionExecuting (ActionExecutingContext filtercontext) {try {              string userName = FilterContext.HttpContext.User.Identity.Name;            This.userid = Username.replace ("china\\", "" "); } catch (Exception) {This.userid = string.            Empty;        }}////Summary://Called by the MVC framework before the operation results are executed.        Parameters://Filtercontext://filter context. public override void Onresultexecuting (ResultExecutingContext filtercontext) {Userlogutils.loguserstati C (This.userid, this. Version, Enumutils.getenumdescbyvalue ((int) this.moduleenum, typeof (Enummodulename)), This.fu        Nctionname); }    }

Add features to the controller inside the method:

Call [Superlogstat (Moduleenum = enummodulename.modulehome, functionname = "Pending Review")] public        ActionResult Myapplytoauditing ()        {            return View ();        }

This actionfilterattribute feature has an unusual interception mechanism, which is the same as the custom exception intercept described earlier.

(3) The use of the above characteristics of the class:

The use of attributes above the class is actually. NET is also a lot. For example, the MEF used to avoid new objects is a compelling example:

When defining a class to implement an interface:

    [Export ("Impc_tb_test", typeof (Ifc_tb_test))]    public class Impc_tb_test:ifc_tb_test    {        ...    }    

Define interfaces without any special:

    Public interface ifc_tb_test    {        ...    }

Then you only need to add an [Import] tag when you use it, and this variable will automatically new a impc_tb_test variable at compile time:

[Import ("Impc_tb_test")] Ifc_tb_test service {get; set;}

When using a service variable, you can use it as a Impc_tb_test object directly. is not very convenient.

These common usage is the blogger used to feel better than the scene, of course, the use of features certainly far more than that, welcome the heroes to make bricks ~ ~

C # Basic Series--attribute features use

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.