首页 > 代码库 > c#接口

c#接口

接口内可以定义:索引器,属性,函数,事件。均不能用访问修饰符访问

 1 public  interface IEventInterFace 2     { 3         string this[int index] { get; set; }//索引器 4         List<string> MyList { get; set; } //属性 5         string Name { get; set; }//属性 6         event EventHandler MyEventHandler;//事件 7         void Meth();//方法 8     } 9 10     public class InterFaceTestClass:IEventInterFace11     {12         public string this[int index]//索引器实现13         {14             15              get16              {17                 if(index>0&&index<=MyList.Count-1)18                   return MyList.ToArray()[index];19                 return "超出边界";20              }21              set22              {23                  MyList[index] = value;24              }25         }26         public List<string> MyList { get; set; } //属性实现27         public  string Name { get; set; }//属性实现28         public void Meth()//方法实现29         {30             Console.WriteLine("Meth");31         }32         public event EventHandler MyEventHandler;//事件实现33 34         public void InvokeMyEventHandler()//调用事件的方法35         {36             MyEventHandler(null, null);37         }38     }39 class Program40     {41         public static void MyMethed(object sender,EventArgs e)42         {43             Console.WriteLine("MyMethed");44         }45 46         static void Main(string[] args)47         {48 49             var myClass=new InterFaceTestClass();50             myClass.MyList=new List<string>(){"a","b","c"};51             var str= myClass[1];//索引器用法52             Console.WriteLine(str);53             54             myClass[1] = "bb";55             myClass.Meth();56             myClass.MyEventHandler+=new EventHandler(MyMethed);//事件添加函数57 58             myClass.InvokeMyEventHandler();59             60            61         }62     }

 

c#接口