您的位置:首页 > 其它

【转】一、特性是什么东东

2018-01-11 11:03 267 查看

【转】一、特性是什么东东

前言

我们初学C#的时候看到类上面一对中括号里面有个高亮了的关键字,不知道那是什么有什么用。想问人又不知道它叫什么。纠结的要命。其实,它就是特性。如:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace net
{
[AttributeUsage(AttributeTargets.All, Inherited = true, AllowMultiple = true)]//3.设置可用于哪些对象
public class TMessgAttribute : Attribute//1.定义类TMessg加上后缀TMessgAttribute 2.继承Attribute。
{
public TMessgAttribute() { }

/// <param name="createTime">创建时间</param>
/// <param name="createName">创建人</param>
public TMessgAttribute(string createTime, string createName, string mess)
{
this._createName = createName;
this._createTime = createTime;
this._mess = mess;
}

private string _createTime;
public string createTime
{
get { return _createTime; }//4.只能有get方法
}
private string _createName;
public string createName
{
get { return _createName; }
}
private string _mess;
public string mess { get { return _mess; } }
/// <summary>
/// 修改时间
/// </summary>
public string modifyTime { get; set; }
}

class Program
{
static void Main(string[] args)
{
System.Reflection.MemberInfo info = typeof(T2Class);
TMessgAttribute[] hobbyAttr = (TMessgAttribute[])Attribute.GetCustomAttributes(info, typeof(TMessgAttribute));//修改1.这里需要取特性数据的集合了
Console.WriteLine("类名:{0}", info.Name);
for (int i = 0; i < hobbyAttr.Count(); i++)//修改2.这里需要循环打印了
{
Console.WriteLine("================================================");
Console.WriteLine("创建人:{0}", hobbyAttr[i].createName);
Console.WriteLine("创建时间:{0}", hobbyAttr[i].createTime);
Console.WriteLine("备注消息:{0}", hobbyAttr[i].mess);
Console.WriteLine("修改时间:{0}", hobbyAttr[i].modifyTime);
}

Console.ReadKey();
}
}

[TMessg("2015-12-20", "zhaopei", "我只是测试自定义特性,不要报错哦,求求你了。", modifyTime = "2015-12-21")]
[TMessg("2015-12-21", "zhaopei", "我再次测试,还能给我面子显示出来吗?", modifyTime = "2015-12-22")]
public class TClass
{
//................
}

public class T2Class : TClass
{
//...........
}
}
View Code

自定义特性可以干什么?

上面我们通过反编译,发现自定义特性实际上就是一个对象调用的最前面加了一段实例化的代码。

那么我们可以做的事可多了,除了像上面一样为对象设置“注释”,我们还可以自定义个特性,给某些方法或是某些类做“操作日志记录”,或者给需要在执行某些方法的时候需要权限,我们可以做个权限认证的特性等等。

这里就需要大家自己去扩展了。

 

本文已同步至《C#基础知识巩固系列》 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: