010- CSharp操作符详解
作者:互联网
操作符详解
一、基础操作符
、1. 自增自检 操作符 ++、--
int x = 100; int y = x++; Console.WriteLine(x);//101 Console.WriteLine(y);//100 注解: x++; 是先用后加,先赋值后加减 详解步骤: int y = x++; 等同于: int y = x; x = x+1;
2. typeof 操作符
// 元数据 metadata Type t = typeof(int);//类型 Console.WriteLine(t.Namespace);//命名空间 System Console.WriteLine(t.FullName);// System.Int32 Console.WriteLine(t.Name);// Int32 int c = t.GetMethods().Length;//查看方法 foreach (var item in t.GetMethods()) { Console.WriteLine(item.Name); } Console.WriteLine(c);
3. default 默认值
double d = default(double); Console.WriteLine(d);//0
4. new 实例操作符
Form form = new Form() { Text = "hello" }; form.ShowDialog(); var person = new {name="aa",age=34 }; Console.WriteLine(person.name); Console.WriteLine(person.age); Console.WriteLine(person.GetType().Name);
5. checked 检查栈溢出
uint x = uint.MaxValue; Console.WriteLine(x); string binStr = Convert.ToString(x ,2); Console.WriteLine(binStr); try { uint y = checked(x +1);//检测是否溢出 Console.WriteLine(y); } catch (OverflowException ex) { Console.WriteLine("There is overflow");//栈溢出 }
6. delegate
委托Delegate是一个类,定义了方法的类型, 使得可以将方法当做另一个方法的参数来进行传递,这种将方法动态地赋给参数的做法
//案例:委托实例 public class LanguageSpeak { public delegate void SpeakLanguageDelegate(string name); public void SpeakLanguage(string name, SpeakLanguageDelegate speakLanguageDelegate) { speakLanguageDelegate(name); } public void SpeakChinese(string name) { Console.WriteLine(name + " speak Chinese"); } } //自己测试 public delegate void learn(string a); public static void chinese(string a) { Console.WriteLine("aaaa"); } public static void Main(string[] args) { LanguageSpeak languageSpeak = new LanguageSpeak(); //languageSpeak.SpeakLanguage("aa",languageSpeak.SpeakChinese); learn a = new learn(chinese); a("11"); Console.ReadKey(); }
强制类型转换
1. 隐式类型转换(implicit)
子类向父类的转换
2. 显示类型转换(explicit)
- 有可能丢失精度的转换,即是cast ; int 实体转换
- 拆箱
- 使用Convert类
- ToSting方法 与 各种数据类型的 Parse、TryParse方法
class Program { public static void Main(string[] args) { Stone stone = new Stone(); stone.Age = 5000; //石头类 强制类型转换 猴子类 Monkey wukongSun = (Monkey)stone; Console.WriteLine(wukongSun.Age); Console.ReadKey(); } } class Stone { public int Age; //explicit 显示转换 public static explicit operator Monkey(Stone stone) { Monkey m = new Monkey(); m.Age = stone.Age; return m; } } class Monkey { public int Age; }
三、算术操作符
- 乘法
- 除法
- 余数
- 加法
- 减法
double a = (double)5 / 4;//1.25 double b = (double)(5 /4);//1.00 整数是整除
四、位移操作符
1. <<
int x = 7; int y = x << 2;//左移两位 string strX = Convert.ToString(x,2).PadLeft(32,'0'); string strY = Convert.ToString(y, 2).PadLeft(32,'0'); Console.WriteLine(strX);//00000000000000000000000000000111 Console.WriteLine(strY);//00000000000000000000000000011100 Console.WriteLine(y);//28 二进制转十进制
五、 关系和类型检测
1. 类型检验操作符 : is as
2. 关系操作符: > <
六、逻辑操作符
1. & 、&& 、 | 、
null 值操作符 : ??
int? x= null; int y= x ?? 1;//if(x == null) x = 1; Console.WriteLine(y);
标签:Console,string,int,010,操作符,WriteLine,CSharp,public 来源: https://www.cnblogs.com/lg-lg/p/15249843.html