c#学习笔记(一)特性、反射、属性、索引器、委托、事件

工程目录:Note

特性:

[attribute(positional_parameters, name_parameter = value, ...)]
element

特性(Attribute)的名称和值是在方括号内规定的,放置在它所应用的元素之前。positional_parameters 规定必需的信息,name_parameter 规定可选的信息。

自建特性DebugInfo:DebugInfo.cs

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

namespace Note
{
    [AttributeUsage(AttributeTargets.Class |
     AttributeTargets.Constructor |
     AttributeTargets.Field |
     AttributeTargets.Method |
     AttributeTargets.Property,
     AllowMultiple = true)]
    class DebugInfo : Attribute
    {
        private int bugNo;
        private string developer;
        private string lastReview;
        public string message;

        public DebugInfo(int bg, string dev, string lastR) {
            this.bugNo = bg;
            this.developer = dev;
            this.lastReview = lastR;
        }

        public int BugNo
        {
            get { return bugNo; }
        }

        public string Developer
        {
            get { return developer; }
        }

        public string LastReview
        {
            get { return lastReview; }
        }

        public string Message
        {
            get { return message; }
            set { message = value; }
        }
    }
}

自建特性在Rectangle类中的应用:Rectangle.cs

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

namespace Note
{
    [DebugInfo(45, "Zara Ali", "12/8/2012", Message = "Return type mismatch")]
    [DebugInfo(49, "Nuha Ali", "10/10/2012", Message = "Unused variable")]
    class Rectangle
    {
        double width;
        double length;
        //构造函数
        public Rectangle(double _width, double _length)
        {
            width = _width;
            length = _length;
        }
        //计算面积
        [DebugInfo(55, "Zara Ali", "19/10/2012", Message = "Return type mismatch")]
        public double getArea()
        {
            return width * length;
        }
        //结果显示
        [DebugInfo(56, "Zara Ali", "19/10/2012")]
        public void Display()
        {
            Console.WriteLine("length:{0}", length);
            Console.WriteLine("width:{0}", width);
            Console.WriteLine("Area:{0}", getArea());
        }
    } 
}

反射:

反射(Reflection)有下列用途:

  • 它允许在运行时查看特性(attribute)信息。
  • 它允许审查集合中的各种类型,以及实例化这些类型。
  • 它允许延迟绑定的方法和属性(property)。
  • 它允许在运行时创建新类型,然后使用这些类型执行一些任务。

在主函数中通过 GetCustomAttributes 函数查看类和方法中的特性信息

属性:

 

属性(Property) 是类(class)、结构(structure)和接口(interface)的命名(named)成员。类或结构中的成员变量或方法称为 域(Field)。属性(Property)是域(Field)的扩展,且可使用相同的语法来访问。它们使用 访问器(accessors) 让私有域的值可被读写或操作。

属性(Property)不会确定存储位置。相反,它们具有可读写或计算它们值的 访问器(accessors)

抽象属性实例:AbstractProperties.cs

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

namespace Note
{
    public abstract class Person
    {
        public abstract string Name
        {
            get;
            set;
        }

        public abstract int Age
        {
            get;
            set;
        }
    }

    class Student : Person
    {
        private string code = "N.A";
        private string name = "N.A";
        private int age = 0;
        //声明code属性
        public string Code
        {
            get { return code; }
            set { code = value; }
        }
        
        //重写name属性
        public override string Name
        {
            get { return name; }
            set { name = value; }
        }

        //重写age属性
        public override int Age
        {
            get { return age; }
            set { age = value; }
        }

        //重写ToString()
        public override string ToString()
        {
            return "   code:" + code + "   name:" + name + "   age:" + age;
        }
    }
}

 

索引器:

索引器(Indexer) 允许一个对象可以像数组一样被索引。当您为类定义一个索引器时,该类的行为就会像一个 虚拟数组(virtual array) 一样。您可以使用数组访问运算符([ ])来访问该类的实例。

实例:IndexedNames.cs

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

namespace Note
{
    class IndexedNames
    {
        public static int size = 10;
        private string[] nameList = new string[size];
        public IndexedNames()
        {
            for (int i = 0; i < size; i++)
            {
                nameList[i] = "N.A";
            }
        }
        //获取size
        public int Size
        {
            get { return size; }
        }
        //定义索引器
        public string this[int index]
        {
            get
            {
                string temp;
                if (index >= 0 && index <= size - 1)
                {
                    temp = nameList[index];
                }
                else
                {
                    temp = "";
                }
                return temp;
            }
            set
            {
                if (index >= 0 && index <= size - 1)
                {
                    nameList[index] = value;
                }
            }
        }
    }
}

委托:

 

C# 中的委托(Delegate)类似于 C 或 C++ 中函数的指针。委托(Delegate) 是存有对某个方法的引用的一种引用类型变量。引用可在运行时被改变。

委托(Delegate)特别用于实现事件和回调方法。所有的委托(Delegate)都派生自 System.Delegate 类。

声明委托(Delegate)

委托声明决定了可由该委托引用的方法。委托可指向一个与其具有相同标签的方法。

实例:DelegateTest.cs

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace Note
{
    //声明委托
    delegate int NumberChanger(int n);
    class DelegateTest
    {
        static int num = 10;
        //ADDNUM 函数
        public static int AddNum(int p)
        {
            num += p;
            return num;
        }

        public static int MultNum(int q)
        {
            num *= q;
            return num;
        }

        public static int GetNum()
        {
            return num;
        }
    }
    //声明委托
    public delegate void printString(string str);
    class PrintString
    {
        static FileStream fs;
        static StreamWriter sw;

        //打印到控制台方法
        public static void PrintToScreen(string str) {
            Console.WriteLine("the string is:{0}", str);
            StreamReader FileContent = new StreamReader("message.txt", Encoding.Default);
            Console.WriteLine(FileContent.ReadLine());
        }

        //打印到文件方法
        public static void PrintToFile(string str)
        {
            fs = new FileStream("message.txt",FileMode.OpenOrCreate,FileAccess.ReadWrite);
            sw = new StreamWriter(fs);
            sw.WriteLine(str);
            sw.Flush();
            sw.Close();
            fs.Close();
        }
        public static void SendString(printString ps)
        {
            ps("this is the delegate test");
        }
    }
}

 

事件:

 

通过事件使用委托

事件在类中声明且生成,且通过使用同一个类或其他类中的委托与事件处理程序关联。包含事件的类用于发布事件。这被称为 发布器(publisher) 类。其他接受该事件的类被称为 订阅器(subscriber) 类。事件使用 发布-订阅(publisher-subscriber) 模型。

发布器(publisher) 是一个包含事件和委托定义的对象。事件和委托之间的联系也定义在这个对象中。发布器(publisher)类的对象调用这个事件,并通知其他的对象。

订阅器(subscriber) 是一个接受事件并提供事件处理程序的对象。在发布器(publisher)类中的委托调用订阅器(subscriber)类中的方法(事件处理程序)。

声明事件(Event)

在类的内部声明事件,首先必须声明该事件的委托类型,然后使用event关键字声明事件

实例:EventTest.cs

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

namespace Note
{
    //定义发布器类
    class EventTest
    {
        private int value;
        //定义委托
        public delegate void NumManipulationHandler();
        //定义事件
        public event NumManipulationHandler NumChange;

        public EventTest()
        {
            this.value = 5;
            OnNumChanged();
        }

        protected virtual void OnNumChanged()
        {
            if(NumChange != null)
            {
                NumChange();
            }
            else
            {
                Console.WriteLine("event not fire");
                Console.ReadLine();
            }
        }
        public void SetValue(int value)
        {
            if(this.value != value)
            {
                this.value = value;
                OnNumChanged();
            }
        }
    }
    //定义订阅器类
    public class SubscribEvent
    {
        public void printf()
        {
            Console.WriteLine("event fire");
            Console.ReadKey();
        }
    }
}

利用事件完成一个热水锅炉日志记录实例:BoilerEventApp.cs

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace Note
{
    class Boiler
    {
        private int temp;
        private int pressure;

        //定义构造函数
        public Boiler(int temp, int pressure)
        {
            this.temp = temp;
            this.pressure = pressure;
        }

        //获取温度函数
        public int getTemp()
        {
            return temp;
        }

        //获取压力函数
        public int getPressure()
        {
            return pressure;
        }
    }
    
    //定义事件发布器
    class DelegateBoilerEvent
    {
        //定义委托
        public delegate void BoilerLogHandler(string status);
        //定义事件
        public event BoilerLogHandler BoilerLogEvent;

        protected virtual void OnBoilerLogEvent(string message)
        {
            if(BoilerLogEvent != null)
            {
                BoilerLogEvent(message);
            }
        }
        public void LogProcess()
        {
            string remarks = "O.K";
            Boiler boiler = new Boiler(100, 12);
            int tempreture = boiler.getTemp();
            int pressure = boiler.getPressure();
            if(tempreture > 150 || tempreture < 80 || pressure > 15 || pressure < 12)
            {
                remarks = "Need Maintenance";
            }
            OnBoilerLogEvent("logging info:\n");
            OnBoilerLogEvent("tempreture:" + tempreture + "   pressure:" + pressure);
            OnBoilerLogEvent("\nmessage:" + remarks);
        }
    }

    //定义日志文件写入类
    class BoilerLogInfo
    {
        FileStream fs;
        StreamWriter sw;

        public BoilerLogInfo(string filename)
        {
            fs = new FileStream(filename, FileMode.Append, FileAccess.Write);
            sw = new StreamWriter(fs);
        }

        //写入log函数
        public void Logger(string info)
        {
            sw.WriteLine(info);
        }

        //回收函数
        public void Close()
        {
            sw.Flush();
            sw.Close();
            fs.Close();
        }
    }

    //定义事件订阅器
    class RecordBoilerInfo
    {
        public static void Logger(string info)
        {
            Console.WriteLine(info);
        }
    }
}

主函数代码如下:

using System;
using System.Reflection;

namespace Note
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            //矩形面积
            Console.WriteLine("---------矩形面积----------");
            Rectangle rectangle = new Rectangle(4.5, 3.5);
            rectangle.Display();
            Console.WriteLine("---------Interface:--------");
            MyInterface myInterface = new MyInterface();
            myInterface.MethodToImplement();
            myInterface.ParentMethodToImplement();
            Console.WriteLine("--------FileStream---------");
            FileIO fileIO = new FileIO();
            fileIO.showData();
            fileIO.Close();
            Console.WriteLine("--------Reflection---------");
            Type info = typeof(Rectangle);
            object[] attributes = info.GetCustomAttributes(true);
            for(int i = 0; i<attributes.Length; i++)
            {
                Console.WriteLine(attributes[i]);
            }
            //遍历类特性
            Console.WriteLine("遍历类特性");
            foreach(Object attribute in info.GetCustomAttributes(true))
            {
                DebugInfo dbi = (DebugInfo)attribute;
                if(dbi != null)
                {
                    Console.WriteLine("bugNo:{0}", dbi.BugNo);
                    Console.WriteLine("developer:{0}", dbi.Developer);
                    Console.WriteLine("last reviewed:{0}", dbi.LastReview);
                    Console.WriteLine("remarks:{0}", dbi.message);
                }
            }
            //遍历方法特性
            Console.WriteLine("遍历方法特性");
            foreach (MethodInfo m in info.GetMethods())
            {
                foreach(Attribute attr in m.GetCustomAttributes(true))
                {
                    DebugInfo dbi = (DebugInfo)attr;
                    if(null != dbi)
                    {
                        Console.WriteLine("bugno:{0},for method:{1}", dbi.BugNo, m.Name);
                        Console.WriteLine("developer:{0}", dbi.Developer);
                        Console.WriteLine("last reviewed:{0}", dbi.LastReview);
                        Console.WriteLine("remark:{0}", dbi.message);
                    }
                }
            }
            //抽象属性
            Console.WriteLine("抽象属性");
            Student stu = new Student();
            stu.Code = "001";
            stu.Name = "Zara";
            stu.Age = 21;
            Console.WriteLine("student info:{0}", stu);
            stu.Age += 1;
            Console.WriteLine("student info:{0}", stu);
            //索引器
            Console.WriteLine("索引器");
            IndexedNames indexedNames = new IndexedNames();
            indexedNames[0] = "Zara";
            indexedNames[1] = "Riz";
            indexedNames[2] = "Nuha";
            indexedNames[3] = "Asif";
            indexedNames[4] = "Davinder";
            indexedNames[5] = "Sunil";
            indexedNames[6] = "Rubic";
            for(int i = 0; i < indexedNames.Size; i++)
            {
                Console.WriteLine(indexedNames[i]);
            }
            //委托
            Console.WriteLine("委托");
            //创建委托实例
            NumberChanger numberChanger1 = new NumberChanger(DelegateTest.AddNum);
            NumberChanger numberChanger2 = new NumberChanger(DelegateTest.MultNum);
            Console.WriteLine("value of num:{0}", DelegateTest.GetNum());
            numberChanger1(25);
            Console.WriteLine("value of num after numberChange1(AddNum):{0}", DelegateTest.GetNum());
            numberChanger2(5);
            Console.WriteLine("value of num after numberChange2(MultNum):{0}", DelegateTest.GetNum());

            //创建委托实例
            printString printString2 = new printString(PrintString.PrintToScreen);
            printString printString1 = new printString(PrintString.PrintToFile);
            PrintString.SendString(printString1);
            PrintString.SendString(printString2);

            //事件
            Console.WriteLine("事件");
            EventTest eventTest = new EventTest();
            SubscribEvent subscribEvent = new SubscribEvent();
            eventTest.NumChange += new EventTest.NumManipulationHandler(subscribEvent.printf);
            eventTest.SetValue(7);
            eventTest.SetValue(11);

            //事件实例:热水锅炉日志排障
            BoilerLogInfo boilerLogInfo = new BoilerLogInfo("BoilerLog.txt");
            DelegateBoilerEvent delegateBoilerEvent = new DelegateBoilerEvent();
            delegateBoilerEvent.BoilerLogEvent += new DelegateBoilerEvent.BoilerLogHandler(RecordBoilerInfo.Logger);
            delegateBoilerEvent.BoilerLogEvent += new DelegateBoilerEvent.BoilerLogHandler(boilerLogInfo.Logger);
            delegateBoilerEvent.LogProcess();
            boilerLogInfo.Close();
            Console.ReadLine();
        }
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值