#define IsText//添加一个宏,接触注释
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks; namespace _002特性
{
[MyText("张三",Id =)]
class Program
{
static void Main(string[] args)
{
Type type = typeof(Program);
object[] obj = type.GetCustomAttributes(false);
foreach (var item in obj)
{
Console.WriteLine(item);
Console.WriteLine(((MyTextAttribute)item).Name);
Console.WriteLine(((MyTextAttribute)item).Id);
}
// Text1();
//Text2();特性Obsolete为true程序就不能使用了
//Text3();
//Text4("张三");
}
[Obsolete("这个程序还可以用一段时间")]
public static void Text1()
{
Console.WriteLine("Text1");
}
[Obsolete("该程序作废,禁止使用",true)]
public static void Text2()
{
Console.WriteLine("Text2");
}
[Conditional("IsText")]//该方法被注释掉了(字符串作为标记进行注释)
public static void Text3()
{
Console.WriteLine("Text3");
}
public static void Text4(string name,[CallerFilePath]string filepath="",[CallerLineNumber]int num=,[CallerMemberName]string filename="")
{
Console.WriteLine("Text4");
Console.WriteLine(name+filepath+num+filename);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace _002特性
{
/*1.特性类尾缀加上Attribute
2.必须引用特性[AttributeUsage]并继承于System.Attribute
3.特性内一般只有属性,没有方法
4.构造函数内可以添加参数
*/
[AttributeUsage(AttributeTargets.Class)]
class MyTextAttribute:System.Attribute
{
private string name;
private int id; public string Name { get => name; set => name = value; }
public int Id { get => id; set => id = value; } public MyTextAttribute(string name)
{
this.Name = name;
}
}
}