索引器常量字段方法

索引器就相当于把类或者结构的实例当做了数组,索引器类似属性,区别在于他们的参数

this关键字来定义索引器,value关键字用于给索引器的set设置值,get取值,set设值

class Indexers<T>
{
private T[] arr = new T[4];
public T this[int i]
{
get { return arr[i]; }
set { arr[i] = value; }
}
}
class test
{
static void Main(string[] args)
{
Indexers<string> stringcollection = new Indexers<string>();
stringcollection[0]= "hello,world";
stringcollection[1] = "2222";
stringcollection[2] = "2222";
stringcollection[3] = stringcollection[2];

Console.WriteLine(stringcollection[0]);
Console.WriteLine(stringcollection[1]);
Console.WriteLine(stringcollection[2]);
Console.WriteLine(stringcollection[3]);
Console.Read();
}
}

常量用const声明并且不可在进行修改,字段是在类或结构中声明的变量,变量的概念是大于字段的

方法签名指的是函数名,返回值,参数,修饰符,权限但是不报告返回类型,这是为了方便重载

operator是定义运算符operator+就是指两个对象相+

class MyClass {
// public const int MyConstant = 12;
// public int MyField = 34;
// public MyClass(){
// Console.WriteLine("Constructor");
// }
// public MyClass(int value) {
// MyField = value;
// Console.WriteLine("Constructor");
// }
// ~MyClass()
// {
// Console.WriteLine("Destructor");
// }
// public void MyMethod() {
// Console.WriteLine("myclass.mymethod");
// }
// public int MyProperty
// {
// get { return MyField; }
// set { MyField = value; }
// }
// public int this[int index]
// {
// get { return 0; }
// set { Console.WriteLine("this[{0}] was set to {1}", index,value); }
// }
// public event EventHandler MyEvent;
// public static MyClass operator+(MyClass a,MyClass b)
// {
// return new MyClass(a.MyField + b.MyField);
// }
// internal class MyNestedClass { };

// }
// class test {
// static void Main()
// {
// MyClass a = new MyClass();
// MyClass b = new MyClass(123);
// Console.WriteLine("myclass.myconstant{0}",MyClass.MyConstant);
// a.MyField++;
// Console.WriteLine("a.myfield={0}",a.MyField);
// a.MyMethod();
// a.MyProperty++;
// Console.WriteLine("a.myproperty={0}",a.MyProperty);
// a[0] = 1;
// //Console.WriteLine(a[3]);
// a.MyEvent += new EventHandler(MyHandler);
// MyClass c = a + b;
// Console.Read();
// }
// static void MyHandler(object sender,EventArgs e)
// {
// Console.WriteLine("test myhandler");
// }
// }

 详见:https://blog.csdn.net/GongchuangSu/article/details/48029937

posted @ 2018-08-31 17:18  小矮子的小胖子  阅读(260)  评论(0编辑  收藏  举报