
·您现在的位置: 云翼网络 >> 文章中心 >> 网站建设 >> 网站建设开发 >> ASP.NET网站开发 >> C#特性的简单介绍
特性应该我们大多接触过,比喻经常使用的[Obsolete],[Serializable]等下面我就主要介绍一个特性的一些用法
摘自MSDN定义:用以将元数据或声明信息与代码(程序集、类型、方法、属性等)相关联。
意思就是把我们自定义的特性或者微软自带的特性和我们的代码进行组合,其实就是为我们某些代码附加一些信息
1.1:[Obsolete]这个预定义特性标记了不应被使用的程序实体
[Obsolete("过时方法")]
PRivate static void OutModed()
{
Console.WriteLine("我是过时的方法");
}
然后引用的时候就出现
如果加上false我们发现在引用的使用就没法编译过去大家可以自己试验下
1.2:[Conditional]这个预定义特性指示编译器应忽略方法调用或属性,除非已定义指定的条件编译符号
private static void Main(string[] args)
{
Debug();
Trace();
}
[Conditional("DEBUG")]
private static void Debug() {
Console.WriteLine("我是debug");
}
[Conditional("TRACE")]
public static void Trace()
{
Console.WriteLine("我是TRACE");
}
当调试成trace模式的时候只能结果:

1.3:[AttributeUsage]描述了如何使用一个自定义特性类。并加上限制
创建一个自定义特性
[AttributeUsage(AttributeTargets.Method)]
public class CustomAttribute:Attribute
{
public string Name { get; set; }
public CustomAttribute(string name)
{
Name = name;
}
}
上面的限制是只能用于方法
[Custom()]//报错
internal class Program
{
private static void Main(string[] args)
{
}
allowMultiple = false。它规定了特性不能被重复放置多次所以下面代码会报错
[Custom("1")] //报错
[Custom("2")]
public void Method()
{
}
先定义一个特性类
[AttributeUsage(AttributeTargets.All,AllowMultiple = true,Inherited = false)]
public class CustomAttribute:Attribute
{
public string Name { get; set; }
public int Age { get; set; }
public CustomAttribute(string name,int age)
{
Name = name;
Age = age;
}
}
然后定义一个基类
[Custom("张三", 3)]
public class Base
{
public static void Method()
{
Console.WriteLine("我具有一个特性");
}
}
public static void GetAttributeInfo(Type t) {
var myattribute = (CustomAttribute)Attribute.GetCustomAttribute(t, typeof(CustomAttribute));
if (myattribute!=null)
{
Console.WriteLine("姓名:{0}\n年龄:{1}", myattribute.Name, myattribute.Age);
}
}
调用
GetAttributeInfo(typeof(Base));

public class Base
{
[Custom("张三", 3)]//方法上
public static void Method()
{
Console.WriteLine("我具有一个特性");
}
}
就改变t的写法:t.GetMethod("Method")这样来获取特性运行效果一样