char 类型字符在内存中是以一个字节来表示的,从0到255,int 是四个字节来表示,把字符变量赋给整型变量就会默认的将字符变量转换成整型。
const是静态常量,所以在编译的时候值就确定下来了
readonly是动态常量,要运行到那一步就会进行赋值。
下面两个例子将很好的解释这个问题。
using System;
class P
{
static readonly int A=B*10;
static readonly int B=10;
public static void Main(string[] args)
{
Console.WriteLine("A is {0},B is {1} ",A,B);
}
}
对于上述代码,输出结果是多少?很多人会认为是A is 100,B is 10吧!其实,正确的输出结果是A is 0,B is 10。
using System;
class P
{
const int A=B*10;
const int B=10;
public static void Main(string[] args)
{
Console.WriteLine("A is {0},B is {1} ",A,B);
}
}
对于上述代码,输出结果又是多少呢?难道是A is 0,B is 10?其实又错了,这次正确的输出结果是A is 100,B is 10
const是静态常量,所以在编译的时候就将A与B的值确定下来了(即B变量时10,而A=B*10=10*10=100),那么Main函数中的输出当然是A is 100,B is 10啦。而static readonly则是动态常量,变量的值在编译期间不予以解析,所以开始都是默认值,像A与B都是int类型,故都是0。而在程序执行到A=B*10;所以A=0*10=0,程序接着执行到B=10这句时候,才会真正的B的初值10赋给B
泛型:通过参数化类型来实现在同一份代码上操作多种数据类型。利用“参数化类型”将类型抽象化,从而实现灵活的复用。
例子代码:
class Program
{
static void Main(string[] args)
{
int obj = 2;
Test<int> test = new Test<int>(obj);
Console.WriteLine("int:" + test.obj);
string obj2 = "hello world";
Test<string> test1 = new Test<string>(obj2);
Console.WriteLine("String:" + test1.obj);
Console.Read();
}
}
class Test<T>
{
public T obj;
public Test(T obj)
{
this.obj = obj;
}
}
输出结果是:
int:2
String:hello world