int a = 10;
int b = 3;
double c = a / b; // 3 与java不一样,可以存放整数
数据类型不兼容 转换
string str = "123";
double d = Convert.ToDouble(str); // d = 132
常量
const int a = 1;
a = 2; // 编译错误
枚举
using System;
using System.Conllections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace enumeration
public enum Gender
{
BOY, GIRL // 如果给BOY赋值2 那么GIRL默认就是3
}
class Program
{
static void Main(string[] args){
int boy = (int)Gender.BOY; // boy = 0 根据下标来转换的
int a = 0;
int b = 5;
Gender gender_boy = Gender.BOY; // 枚举取值
Gender a = (Gender)a; // a = BOG 拿到下标为0的值
Gender b = (Gender)b; // b = 5 没有下标为5的枚举,不报错
string str = "0"; // 数字类型不会报错 str=BOY,GIRL不会报错 字符找不到时会报错
Gender gender_str = (Gender)Enum.Parse(typeof(Gender),str)
}
}
结构 静态 方法
using System;
using System.Conllections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace structure
public struct Person // struct结构不具备面向对象的三大特性
{
public string _name; // 字段 public修饰 Main方法体才能调用
public int _age; // 字段能存多个值 变量只能存一个值
public Gender _gender; // 下划线代表字段 规范写法
}
public enum Gender
{
BOY, GIRL
}
class Program
{
public static int _number = 10; // static修饰 整个类都可以直接使用 模拟全局变量
static void Main(string[] args){
Person zsPerson;
zsPerson._name = "张三";
zsPerson._age = 21;
zsPerson._gender = Gender.BOY;
Person lsPerson;
zsPerson._name = "李四";
zsPerson._age = 22;
zsPerson._gender = Gender.GIRL;
public static void Test(_number) // 与java不一样 不用再写类型
{
a = a + 5;
}
}
}
Test(10,out b,out c) // 返回值 b = 12 c = 310
public static void Test(int a, out int b, out string c) // 被out修饰的参数会返回,可修饰多个参数返回多个值
{
b = 2 + a; // out的每个参数必须赋值 否则编译错误
c = 3 + a
}
---------------------------------------------------------------------------
bool b = int.TryParse("123", out num); // 字符串转数字
// 模拟TryParse方法,转换成功返回true num是转换后的值,转换失败返回false num默认值0
public static bool MyTryParse(string str, out int num)
{
num = 0; // 设置默认值
try // 如果转换失败会报错,捕获异常处理
{
num = Convert.ToInt32(str); // string类型 转 int类型
return true;
}
catch
{
return false;
}
}
ref
static void Main(string[] args)
{
int a = 10;
int b = 20;
Test(ref a, ref b); // ref修饰的参数 必须赋值
Console.WriteLine(a); // 510 被重新赋值了
Console.WriteLine(b); // 520
Console.ReadKey();
}
// 被ref修饰的参数会返回,且直接赋值给对应参数
public static void Test(ref int a , ref int b)
{
a += 500;
}
get set
// 底层代码跟java一样
public string Name;
public string Name
{
get { return name; }
set { name = value; }
}
public int Age
{
get;
set;
}
params
// params修饰的参数是可变参数 必须放最后 否则编译错误
// 求任意整数长度数组的和
// 调用方法
getSum(1, 3, 8, 9, 16, 2);
// int[] nums = {1, 3, 8, 9, 16, 2}
// getSum(nums);
public static int getSum(params int[] num)
{
int sum = 0; // 总和
for (int i = 0; i < num.Length; i++)
{
sum += n[i];
}
return sum;
}
// 相当于java中的多态
// is 判断类型转换 true false
bool flag = Children is Parent; // flag = false
// 通过继承后 as 表示类型转换
Children children = Parent as Children;
// 跟as差不多
Children children = (Children)Parent;