c#进阶
属性
public static int Num
{
get;//只读
set;//只写
}
public static int Num
{
get
{
return num;
}//只读
set
{
num = value;
}//只写
//关于属性,应该在适当的时候对他进行初始化
}
static void Main(string[] args)
{
Num = 100;
Console.WriteLine("hello world" Num);
Console.ReadLine();
}
泛型
使用:我们在写代码的时候经常会遇到逻辑一样的代码,只有数据类型不同,这时候哦们可以通过使用泛型来让代码更高效.
static void SwapInt(ref int a,ref int b){
int temp;
temp = a;
a = b;
b = temp;
}
static void SwapInt(ref float a,ref float b){
float temp;
temp = a;
a = b;
b = temp;
}
static void Main(string[] args)
{
Console.WriteLine("交换前 a:{0} b:{1}",a,b);
SwapInt(ref a, ref b);
Console.WriteLine("交换后a:{0} b:{1}",a.b)
Console.ReadLine();
int 为值类型,下方修改并不能更改其真正的值,只会重新在栈上开辟一段内存,若想改变其值,必须使用引用类型,需要加ref,传递引用型参数.
}
泛型
把一个类型当成一个参数,就是泛型
static void SwapInt<T>(ref T a,ref T b)//泛型的声明并不需要注明使用的是什么类型,用的时候指定他的数据类型
{
T temp;
temp = a;
a = b;
b = temp;
}
Swap<int>(ref a,ref b);
类委托接口皆可以使用泛型
泛型类:
class MyTest<T>{}//泛型类声明
MyTest<T> strs = new MyTest<string>(2);//泛型类的使用方法,2表示两个数据
strs.test[0] = "hello";//0表示第0位
strs.test[1] = "world";//1表示第一位
static void Swap<T>(ref T a,ref T b)
{
}