一点一点学C#1
C#内置引用类型:object String Dynamic
C#完全面向对象,没有所谓的全局变量,取消了指针的使用,实例声明用new,抛弃了多继承,拥有自动内存管理
数据输出转换相关:
using System;namespace test1
{class test1{static void Main(String[] args){//显示强制转换double a = 22.23;int i = (int)a;Console.WriteLine(i);//C#内置类型转换方法float f = 0.12f;Console.WriteLine(f.ToString());//object,类型检测在编译时发生object o;o = 100; //装箱Console.WriteLine("o = {0}",o);int b = (int)o; //拆箱Console.WriteLine("b = {0}",b);//dynamic,类型检测在运行时发生dynamic c = 99,d = 1.23;Console.WriteLine("c = {0},d = {1}",c,d);//字符串StringString str1 = "gbb";String str2 = @"/ybb"; //字符串前面加@,里面的特殊字符当做普通字符输出String str3 = "a b" + //字符串里可以任意换行、空格"c";Console.WriteLine(str1);Console.WriteLine(str2);Console.WriteLine(str3);Console.ReadKey();}}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace ConsoleApplication1
{class Program{static void Main(string[] args){String str1 = "gbb" + Environment.NewLine + "ybb"; //字符串中有换行回车的正确方式Console.WriteLine("str1:\n{0}",str1);String str2 = "gbb\r\nybb"; //字符串中硬编码了回车符和换行符,一般不建议,这样有可能不支持跨平台Console.WriteLine("str2:\n{0}",str2);//字符串可以使用“+”连接String str3 = "abc" + " " + "def";Console.WriteLine("str3:{0}",str3);Console.ReadKey();}}
}
整数常量的前缀、后缀:均不区分大小写
0x 十六进制 0 八进制 无前缀 十进制
后缀:
U unsigned L long
using System;namespace test1
{class test1{static void Main(String[] args){Console.WriteLine("input a inteager:");int num;num = Convert.ToInt32(Console.ReadLine()); //readLine()只接受字符串Console.WriteLine("the number input:{0}",num);//进制转换decimal d = (decimal)0x20; Console.WriteLine("转换为十进制为:{0}",d);Console.ReadKey();}}
}
访问修饰符进行C#的封装:
public 任何公有成员可以被外部类访问
private 同一个类中的函数成员可以访问
protected 子类访问基类的成员函数成员变量,有助于实现继承
internal 可被同一应用程序中的任何类或方法访问
protected internal
引用 ref
using System;namespace test1
{class test1{public int num = 50; //不加public则不能被其他类调用public int getMax(ref int a,ref int b) //传引用,public作用同上//protected internal int getMax(ref int a,ref int b) //用protected internal也可以,不太明白,做个标记{if(a > b){return a;}else {return b;}}}class test2{public static void Main(String [] args){test1 t = new test1();int x = 20,y = 30;Console.WriteLine("The Max:{0},the number:{1}",t.getMax(ref x,ref y),t.num);Console.ReadLine();}}}
可空类型&空值合并
using System;namespace test1
{class test1{public static void Main(String [] args){//可空类型 ?bool ?val = new bool?();int ? num1 = null;int ? num2 = 20;double ? num3 = null;float ? num4 = 1.23f;double ? num5 = new double?();Console.WriteLine("{0},{1},{2},{3},{4},{5}",val,num1,num2,num3,num4,num5);//null的合并运算 ??int num;num = num1 ?? 9;Console.WriteLine("num:{0}",num);//第一个数为空,返回第二个数的值num = num2 ?? 9;Console.WriteLine("num:{0}",num);//第一个数非空,返回第一个数的值Console.ReadLine();}}
}
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
