C#学习笔记(三)

it2022-05-05  119

特性Attribute

特性是用于运行时,传递程序中的各种元素的行为信息的声明性标签,通过放置在它所使用的元素的方括号[]来进行描述。

特性用于添加元数据,如编译器指令和注释、描述、方法、类等

ConditionalAttribute

ConditionalAttribute是用来做判断条件的,只有满足了相应的条件,程序才会执行,必须出现在相应的代码前面,当有多个Attribute的时候,只需要依次加上([])即可,不需要在乎顺序,Attribute实际上是一种比较特殊的实例化的类,这种操作类似于C语言里面的宏。

条件属性必须是类声明或者结构声明中使用,如果用在接口中声明会报错。条件方法必须有返回类型。

写一段简单的测试代码来使用ConditionalAttribute:

#define Triangle using System; using System.Diagnostics; namespace AttributeApplication { class AttributeTest { [Conditional("Triangle")] public static void getTriangle() { Console.WriteLine("15"); } [Conditional("Circle")] public static void getCircle() { Console.WriteLine("Circle"); } static void Main(String[] args) { getTriangle(); getCircle(); } } }

上述代码的执行结果如下所示:

可见只有定义了相应的宏才能够执行相应的代码。

obsolete

obsolete特性的方法会被标志为是过时的,程序会显式相应的警告信息,自己写的一份学习代码如下所示:

可以发现出现了相应的警告条,如果想要使用Obsolete的方法,可以在Main函数的前面加上Obsolete,如下所示:

Self-define

#define Triangle using System; using System.Diagnostics; namespace AttributeApplication { [AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited =true)] public class developerInfo : Attribute { private string name; private string date; public string Name { get { return name; } set { name = value; } } public string Date { get { return date; } set { date = value; } } public developerInfo(string _name, string _date) { this.name = _name; this.date = _date; } } [developerInfo("Alva", "2019-07-18")] class Test { } class AttributeTest { static void Main(string[] args) { Test test = new Test(); Type t = typeof(Test); foreach (developerInfo attribute in t.GetCustomAttributes(false)) { Console.WriteLine("Name: {0}", attribute.Name); Console.WriteLine("Date: {0}", attribute.Date); } } } }

反射Reflection

反射的用途如下:

允许在运行时查看特性信息允许审查集合中的各种类型允许延时绑定的方法和属性允许运行时创建新类型

索引器Indexer

using System; namespace indexApplication { class indexApp { private string[] name = new string[100]; public string this[int index] { get { if (index >= 0 && index < 100) { return name[index]; } else { return ""; } } set { if (index >= 0 && index < 100) { name[index] = value; } } } } class indexExecution { static void Main(string[] args) { indexApp t = new indexApp(); t[0] = "Sam"; t[1] = "Susan"; t[2] = "Alva"; Console.WriteLine(t[0]); Console.WriteLine(t[1]); Console.WriteLine(t[2]); } } }

最新回复(0)