当前位置:网站首页>C# 特殊语法

C# 特殊语法

2022-06-09 05:59:00 Go_Accepted

1、var隐式类型

var是一种特殊的变量类型,可以用来表示任意类型的变量

注意:

(1)var不能作为类的成员,只能用于临时变量的申明时,也就是一般写在函数语句块中

(2)var必须初始化,但初始化后类型就定了

var i = 5;
var s = "srea";
var array = new int[] { 1, 2, 3, 4 };
var list = new List<int>();

2、设置对象初始值

声明对象时,可以通过直接写大括号的形式初始化公共成员变量和属性

class Person {
    private int money;
    public bool sex;

    public string Name {
        get;
        set;
    }

    public int Age {
        get;
        set;
    }
}

Person p = new Person { sex = true, Age = 17, Name = "person" }; //无参构造 小括号可以省略
Person p2 = new Person() { sex = true };

如果是有参构造,那么直接在小括号里传入相关参数即可

3、设置集合初始值

声明集合对象时,也可以通过大括号直接初始化内部属性

int[] array = new int[] { 1, 2, 3, 4, 5 };
List<int> list = new List<int>() { 1, 2, 3, 4, 5 }; // 小括号也可以省略
List<Person> listPerson = new List<Person>() {
    new Person(),
    new Person(){Age = 10},
    new Person(){sex = true, Name = "test"}
};

Dictionary<int, string> dic = new Dictionary<int, string>() {
    {1, "123" },
    {2, "222" }
};

4、匿名类型

var变量可以声明为自定义的匿名类型

var v = new { age = 10, money = 11, name = "Ming" };
Console.WriteLine("{0}, {1}, {2}", v.age, v.money, v.name);

不能将Lambda表达式添加在匿名类型

5、可空类型

(1)值类型是不能赋值为空的,即 int a = null; 是不行的

(2)声明时,在值类型后面加?,可以赋值为空

int? a = null;  

(3)判断是否为空

if (a.HasValue) {
    Console.WriteLine(a);
    // 等效于
    Console.WriteLine(a.Value);
}

注意:不能直接将a赋值给int类型的变量,即 int v = a;   是错误的,必须通过 Value 取对应的值:int v = a.Value;

(4)安全获取可空类型值

如果为空,默认返回值类型的默认值

Console.WriteLine(a.GetValueOrDefault());

也可以指定一个默认值

Console.WriteLine(a.GetValueOrDefault(100));

但是这里并不会把 a 的值赋为100

(5)配合引用类型的用法:

object o = null;
if (o != null) {
    o.ToString();
}

Action action = null;
if (action != null)
    action.Invoke();

可以简写为

o?.ToString();

action?.Invoke();

对于数组:

int[] array = null;
Console.WriteLine(array?[0]);

相当于是一种语法糖,能够帮助自动去判断是否为空,如果是空就不会执行后面的方法

6、空合并操作符

空合并操作符 ??

格式:左边值 ?? 右边值

如果左边值为null,就返回右边值,否则返回左边值

只要是可以为null的类型都能用

类似于三目运算符

int? intV = null;
int intI = intV == null ? 100 : intV.Value;
intI = intV ?? 100;

7、内插字符串

关键符号:$

用$来构造字符串,让字符串中可以拼接变量

string name = "ming";
int age = 19;
Console.WriteLine($"hello world,{name},{age}");

8、单句逻辑简略写法

通常说法就是单句可以省略大括号,主要还是说类中属性和函数的写法

public string Name {
    get => "test";
    set => name = value;
}

public int Add(int a, int b) => a + b;
public void Speak(string str) => Console.WriteLine(str);
原网站

版权声明
本文为[Go_Accepted]所创,转载请带上原文链接,感谢
https://blog.csdn.net/Go_Accepted/article/details/125105422