`
北极的。鱼
  • 浏览: 150699 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

关于C#中的特性小例子

阅读更多

最近要写一个网络报表。

众所周知,网络报表是程序员的一大噩梦。

幸运的是,了解了下需求,然后去网络上大概看了下报表相关的信息。

感觉微软自带的RDLC报表能完全满足需求了。

不过,受伤的总是我。

老大一句:“要做成组件,下次调用直接拖拉就行,不需要手动操作!”

...

请问:天黑是神马感觉?!

这句话的意思就是要完全动态生成报表(不了解rdlc报表的童鞋们去操作下试试就知道了)。

里面要用到的技术,我大概想了一下。

主要就是XML的架构定义和序列号,反序列话。其他的没什么。不过,就这2个技术,让我感觉顿时落入了地狱(两个我都不熟悉。)。

没办法,只能硬着头皮搞了。

第一个遇到的问题就是c#特性机制了。

稍微看了下,懂了,就先记录下一些自认为经典的例子吧(2个小时前,我连这个[]叫特性都不知道,或者说都没怎么见过这个运算符这个用。2个小时看了几个代码,尤其是下面示例的代码,就懂了!)。

 

不多说,如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            BoardingCheckAttribute boardingCheck = null;
            object[] customAttributes = typeof(HumanPropertyBase).GetCustomAttributes(true);
            Console.WriteLine(typeof(HumanPropertyBase).IsSerializable);
            foreach (System.Attribute attribute in customAttributes)
            {
                if (attribute is BoardingCheckAttribute)
                {
                    boardingCheck = attribute as BoardingCheckAttribute;
                    Console.WriteLine(boardingCheck.Name
                        + "'s ID is "
                        + boardingCheck.ID
                        + ", he/she wants to "
                        + boardingCheck.Destination
                        + " from "
                        + boardingCheck.Departure
                        + " by the plane "
                        + boardingCheck.FlightNumber
                        + ", his/her position is "
                        + boardingCheck.PositionNumber
                        + ".");
                }
            }

            Console.ReadLine();
        }
    }
    [Serializable]
    [BoardingCheckAttribute("123","louis",22,12,"aaaa","ccccc")]
    public class HumanPropertyBase
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public int Gender { get; set; }

        [Obsolete("I'm so old, don't kill me!", true)]
        public void Run(int speed)
        {
            // Running is good for health.  
        }
    }

    public class BoardingCheckAttribute : Attribute
    {
        public string ID { get; private set; }
        public string Name { get; private set; }
        public int FlightNumber { get; private set; }
        public int PositionNumber { get; private set; }
        public string Departure { get; private set; }
        public string Destination { get; private set; }

        public BoardingCheckAttribute(string id, string name, int flightNumber, int positionNumber, string departure, string destination)
        {
            this.ID = id;
            this.Name = name;
            this.FlightNumber = flightNumber;
            this.PositionNumber = positionNumber;
            this.Departure = departure;
            this.Destination = destination;
        }

    }

}

 

 

[System.AttributeUsage(System.AttributeTargets.Class |
                       System.AttributeTargets.Struct,
                       AllowMultiple = true)  // multiuse attribute
]
public class Author : System.Attribute
{
    string name;
    public double version;

    public Author(string name)
    {
        this.name = name;
        version = 1.0;  // Default value
    }

    public string GetName()
    {
        return name;
    }
}

[Author("H. Ackerman")]
public class FirstClass
{
    // ...
}

// No Author attribute
public class SecondClass
{
    // ...
}

[Author("H. Ackerman"), Author("M. Knott", version = 2.0)]
public class ThirdClass
{
    // ...
}

class TestAuthorAttribute
{
    static void Main()
    {
        PrintAuthorInfo(typeof(FirstClass));
        PrintAuthorInfo(typeof(SecondClass));
        PrintAuthorInfo(typeof(ThirdClass));
    }

    private static void PrintAuthorInfo(System.Type t)
    {
        System.Console.WriteLine("Author information for {0}", t);
        System.Attribute[] attrs = System.Attribute.GetCustomAttributes(t); // reflection

        foreach (System.Attribute attr in attrs)
        {
            if (attr is Author)
            {
                Author a = (Author)attr;
                System.Console.WriteLine("   {0}, version {1:f}", a.GetName(), a.version);
            }
        }
    }
}

 

网上搜到的解释:(对应第二段代码)

 

使用反射访问属性(C# 编程指南)
如果没有检索自定义属性的信息和对其进行操作的方法,则定义自定义属性并将其放置在源代码中就没有意义。C# 具有一个反射系统,可用来检索用自定义属性定义的信息。主要方法是 GetCustomAttributes,它返回对象数组,这些对象在运行时等效于源代码属性。此方法具有多个重载版本。有关更多信息,请参见 Attribute。

属性规范,如:

C#
[Author("H. Ackerman", version = 1.1)]
class SampleClass

在概念上等效于:

C#
Author anonymousAuthorObject = new Author("H. Ackerman");
anonymousAuthorObject.version = 1.1;

【备:我是第一次看到这个写法,然后兴匆匆的去试了下类的属性,发现这个写法不使用了。

   疑惑:难道这个写法只适用于特性的实例化么?如果高手见到,还请指教。】

但是,直到查询 SampleClass 以获取属性时才会执行此代码。对 SampleClass 调用 GetCustomAttributes 会导致按上述方式构造并初始化一个 Author 对象。如果类还有其他属性,则其他属性对象的以类似方式构造。然后 GetCustomAttributes 返回 Author 对象和数组中的任何其他属性对象。之后就可以对此数组进行迭代,确定根据每个数组元素的类型所应用的属性,并从属性对象中提取信息。

分享到:
评论
1 楼 北极的。鱼 2011-05-26  
请记住:
属性:是面向对象思想里所说的封装在类里面的数据字段。
特性:不需要你生理上包含这些属性,就像上面的HumanBase类没有IsSerializable这样的属性,特性只需要在类或方法需要的时候加上去就行了。

就相当于:
属性是人天生的特征,而特性是以后你需要是时候才获得的特征。

相关推荐

    c#中的特性(attribute)+反射的一个例子

    c#中的特性(attribute)+反射的一个例子

    c#标签特性简单例子可执行

    c#标签特性简单例子可执行,对属性值进行运行时检测. 通过反射

    c# 自定义特性demo

    C# 自定义特性 例子

    C#2017实现自定义属性实现多个标签叠加特性简单例子可执行

    C#2017实现自定义属性实现多个标签叠加特性简单例子可执行

    C#2017实现自定义属性实现标签特性简单例子可执行

    C#2017实现自定义属性实现标签特性简单例子可执行 C#2017实现自定义属性实现标签特性简单例子可执行

    C#高级特性

    一些语法,例子等等 相关的C#的用法,特性,高级运用,与实例,方便使用

    C#开发技术大全

    《C#开发技术大全》的一大特色就是书中的每个例子都经过精挑细选,具有较强的针对性,力求使读者通过书中的示例,能够更迅速地掌握相关知识。此外,《C#开发技术大全》的知识全面,同时具有较强的指导性,可以帮助...

    在一小时内学会 C#(txt版本)

    对 C++ 来说,前面例子中 Date 类的属性就是 day、month 和 year,而你添加了 Get 和 Set 方法。C# 提供了一种更加便捷、简单而又直接的属性访问方式。 所以上面的类应该写成这样: 复制内容到剪贴板 代码: using ...

    C#微软培训资料

    14.4 继承中关于属性的一些问题.169 14.5 小 结 .172 第四部分 深入了解 C#.174 第十五章 接 口 .174 15.1 组件编程技术 .174 15.2 接 口 定 义 .177 15.3 接口的成员 .178 15.4 接口的实现 .182 ...

    C#5.0本质论第四版(因文件较大传的是百度网盘地址)

    11.5.1 在C# 4.0中使用out类型参数修饰符允许协变性 331 11.5.2 在C# 4.0中使用in类型参数修饰符允许逆变性 332 11.5.3 数组对不安全协变性的支持 335 11.6 泛型的内部机制 335 11.6.1 基于值...

    Essential C#6.0 第五版 中文版(uncle-wuc).rar

    Essential C#5.0 第四版 中文版 本书为了帮助读者理解各种C#构造,书中使用了大量例子演示每一种特性,而且为每个概念都提供了相应的规范和最佳实践

    最好的C#入门讲义PPT(英文版)

    最好的C#入门讲义PPT,讲解的很透彻,而且可以帮助用户理解C#的语言特性,其富含例子和图例。

    Illustrated C# 2008 (with Source Code)

    4: 本书把C# 3.0中的新特性也很好地融入内容,非常好,比如lamda表达式和Linq,对于ASP.net开发支持非常有力,但是基本上ASP.net的相关资料中,都不会详细介绍它们的原理,使你感觉很难理解,而这本书则从最基础的...

    【好书推荐】C# 4.0 in a Nutshell, 4th Edition

    对概念和例子独特地组织起来,在这个第4版里,涵盖了新版 C# 的深层次内容,如并联编程、代码契约、动态编程、安全性和对 COM 的相互操作等。你也可以找到最新的 LINQ 信息,包括 LINQ to SQL 和 Entity Framework ...

    c#学习笔记.txt

    C#学习笔记(2)【大 中 小】【打印】【加入收藏】【关闭】 【收藏到新浪ViVi】【收藏到365KEY】 浏览字号:日期:2004-07-11 人气:8092 出处: write by cash(天下第七) 2002.01.20 版权所有,翻录不究 cashcao@...

    C#职场最精髓Webapi实例(Demo含源码,前后端分离,终身受益).rar

    此项目是C#语言编写,以最真实职场做项目的技术,WebAPI特性路由+前后端调用分离技术,非常适用于刚入行IT的新人和不懂Web api的朋友们,直接可用,现成项目,UI+DAL间隔分明,数据网格自动获取配置文件动态加载显示...

    c# Linq WebService rss

    •SampleQueries: 这是最重要的示例,其中包含了 500 多个关于如何在 LINQ to Objects、LINQ to SQL、LINQ to XML 和 LINQ to DataSet 中使用各个查询运算符的例子。 •SimpleLambdas: 几个关于如何编写和使用 ...

    深入理解C#中的String

    关于C#中的类型  在C#中类型分为值类型和引用类型,引用类型和值类型都继承自System.Object类,几乎所有的引用类型都直接从System.Object继承,而值类型具体一点则继承System.Object的子类,即继承System.Value...

    ASP.NET c# ListView 实例

    ASP.NET c# ListView 实例 ASP.NET3.5提供了一个新的控件ListView,它提供了非常优秀的自定义和扩展特性,比之前版本的gridview好用,使用这些新特性,你可以以任何格式显示数据,使用模板和样式,同时用最少的代码...

Global site tag (gtag.js) - Google Analytics