C# Basic Series – Trobut Functions

Introduction: C# core chain previous – reflection notes Summarize the basic usage of the following reflection. Let’s look at another basic C# technology.

1. What is the attribute: According to the blogger’s understanding, properties add tags to the class name, attributes, methods, etc. Some special disciplines are needed. For example, the abnormal catch method, you still use try… catch. Nowadays, if you use properties, you can greatly reduce the use of try… catch. You only need to define a generic ExceptionExattribute class that specializes in Exception, and then do some special processing on that generic class, such as adding an AOP binding function (AOP binding methods are many, if you are interested in the article). Then add the function label [ExceptionEx] For a name that may sound unnatural. This method has the ability to automatically catch anomalies. Or the official definition:

Functions provide powerful ways to bind metadata or declaration information to your code (serialization, type, method, attribute, etc.).Once the properties are bound to the action object, the query specification, called “reflection”, can be used at runtime.

Features have the following features:

  • Properties can be added to the program.Mineral data is a kind of information specified in the program.All .NET assemblies include a specific set of metadata that describes the types, types, types, and hub types.You can add custom properties to provide any additional information you need.

  • One or more functions can be applied to the entire collection of an assembly, a module, or a smaller program element (such as a class and attributes).

  • Features can take parameters just like methods and attributes.

  • The program can use reflection to check metadata or other programs.

(up from MSDN)

2. Why do you need properties: This is briefly introduced above, and properties properties greatly reduce the amount of code for a single request. Not to mention that at least it can make our code more atmospheric~~

3. Typical use: Bloggers still plan to introduce the common usage methods of the three conveniences this time. Of course, these methods have been used by bloggers. This may not be the best example, but it is also a typical usage characteristic.

(1) Use class attributes:

The reason for introducing this in the previous introduction is that the blogger’s recent BS project is in use, and the usage scenario is also typical. First of all, imagine the scene: there is a request for a recent project, and the BS interface requires a drag function. As follows


When you drag 3 commas from left to right, each element has its own unique attributes. For example, when two partitions are dragged, the following attributes should be displayed:


Corresponding attributes may differ when sections 1 and 3 are withdrawn.

Design ideas: a template corresponding to each DIV element, each template has its own unique attributes, and then adds the default value and value of the attribute to the attribute to display the attribute, and the HTML label to be rendered in the interface.

Code execution:

First look at the Single Characteristics 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; }

Suitable Model:

   public class Factory
        [Detail(AttrName="ширина", Html="<input type="text" />", DefaultValue="50", DataSource=null)]
        public string Width { set; get; }

        [Detail(AttrName = "высокий", Html = "<input type="text" />", DefaultValue = "50", DataSource = null)]
        public string Height { set; get; }

        [Detail(AttrName = "государство", Html = "<select></select>", DefaultValue = null, DataSource = "select text,value from status")]
        public string Status { set; get; }

        [Detail(AttrName = "Значение тега", Html = "<input type="text" />", DefaultValue = "", DataSource = null)]
        public string Tag { set; get; }

    public class FactoryDetail
        [Detail(AttrName = "ширина", Html = "<input type="text" />", DefaultValue = "50", DataSource = null)]
        public string Width { set; get; }

        [Detail(AttrName = "высокий", Html = "<input type="text" />", DefaultValue = "50", DataSource = null)]
        public string Height { set; get; }

        [Detail(AttrName = "государство", Html = "<select></select>", DefaultValue = null, DataSource = "select text,value from status")]
        public string Status { set; get; }

        [Detail(AttrName = "Значение тега", Html = "<input type="text" />", DefaultValue = "", DataSource = null)]
        public string Tag { set; get; }
        [Detail(AttrName = "описывать", Html = "<input type="text" />", DefaultValue = "", DataSource = null)]
        public string Desc { set; get; }

Then, at the end of the interface’s pull event, send an AJAX request to represent the interface’s HTML:

        helper: "clone",
        scroll: true,
        drag: function (event, ui) {
            //   debugger;
        drop: function (event, ui) {
            //  debugger;
            if (ui.draggable[0].className.indexOf("jq-draggable-outcontainer") > 0) {
                var text = ui.draggable[0].innerText.trim();
                $(this).append('<div class="window jq-draggable-incontainer" οnclick="GetPropertiesByType(\'1\',this)" style="position:absolute;left:' +(event.clientX-20) + 'px;top:' + (event.clientY-20) + 'px" id="window' + iIndex + '"><strong>' + text + '</strong></div>');

                cur_selector = $("#window"+iIndex);
                $.Ewin.AjaxPost("/Home/GetModelByType", { strType: "Factory" }, function (data, status) {
                    var element = $.parseJSON(data.Json);
                    var arrProp = element.element.property;
                    //0. Строительство HTML
                    var strHtml = "<div style="float:right;padding-top:0px;width:300px;height:auto;"><table cellpadding='5' border="1">";
                                         // 1. Борьба с атрибутом конструктора HTML
                    strHtml += "</table></div>";
                }, function () {

                }, null);


C# matching method:

     public JsonResult GetModelByType(string strType)
// strtype прошел через фабрику или завод
var assembly = Assembly.Load("Ewin.Client.Web");//Имя параметра - это имя сборки var oType = assembly.GetType("Ewin.Client.Web.Controllers." + strType);
// все атрибуты класса
var lstProperties = oType.GetProperties(); foreach (var oProperty in lstProperties) {
// Получить характерный набор каждого атрибута IList
<CustomAttributeData> lstAttr = oProperty.GetCustomAttributesData(); foreach (var oAttr in lstAttr) {
// Получить полное имя каждого характерного класса Console.WriteLine(
"Название характерного класса" + oAttr.AttributeType.FullName); Console.WriteLine("Особенности участники заключаются в следующем:");
// Получить все параметры характерного класса
var lstAttrArgu = oAttr.NamedArguments; foreach (var oAttrAru in lstAttrArgu) {
// возьмите значение ключа каждого характерного параметра класса Console.WriteLine(oAttrAru.MemberName
+ "=" + oAttrAru.TypedValue.Value); } //Console.WriteLine(oAttr.AttributeType+"——"+oAttr.NamedArguments); } } return Json(new { }, JsonRequestBehavior.AllowGet); }

The getModelbyType method is simply created, then the attribute key value is returned to the JS method, and then the JS is added to the interface. Thus, the combination of characteristics and reflection can quickly complete the design of this small function.

(ii) Using the Separation Method Method:

There’s a lot more to using the .NET Framework if you’re using a filter in MVC:

8f900a89c6347c561fdf2122f13be562 View the code

Add functions to the method in the controller:


[SuperLogStat(ModuleEnum = EnumModuleName.ModuleHome, FunctionName = "Быть рассмотренным")]

        public ActionResult MyApplyToAuditing()
            return View();

In this distinct use of this function, there is an anomalous trap mechanism similar to the previously mentioned anomalous trap.

(iii) Use of the above characteristics:

The use of the above class properties is actually a lot of .NET. For example, using MEF to avoid new objects is a very convincing 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

No custom definition interface:

    public interface Ifc_TB_Test

Then you need to add a tag [Impoort] when using it. This variable will automatically create the IMPC_TB_TEST variable:

 Ifc_TB_Test service { get; set; }

When using a service variable, you can use it directly as an IMPC_TB_TEST object. Is it very convenient?

This common use is the best viewer used by bloggers. Of course, the use of properties should be much more than that. Heroes welcome to repair bricks~~

This article is taken from the Lazy blog, the original link: http://www.cnblogs.com/landeanfen/p/4642819.html, if you need to reprint, please contact the original author yourself.

Leave a Comment