关于UnityC#当中常见的语法糖

1自动实现属性 (Auto-implemented Properties):快速实现对象封装

// 传统属性
private int age;
public int Age
{
    get { return age; }
    set { age = value; }
}

// 自动实现属性
public int Age { get; set; }

2对象和集合初始化 (Object and Collection Initializers):快速初始化对象和集合

// 对象初始化
Person person = new Person { Name = "John", Age = 30 };

// 集合初始化
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };

3空值条件运算符 (Null-conditional Operator):

// 传统空值检查
if (person != null && person.Address != null)
{
    // 访问地址属性
}

// 空值条件运算符
if (person?.Address != null)
{
    // 访问地址属性
}

4空合并运算符 (Null-coalescing Operator):

int age = (person != null) ? person.Age : -1;

// 使用空合并运算符
int age = person?.Age ?? -1;

5Lambda表达式 (Lambda Expressions):

Func<int, int> square = delegate(int x) { return x * x; };

// 使用Lambda表达式
Func<int, int> square = x => x * x;

6使用语句处理IDisposable对象 (Using Statement for IDisposable Objects):

// 不使用using语句
FileStream fs = new FileStream("file.txt", FileMode.Open);
// 使用文件流
fs.Close();

// 使用using语句
using (FileStream fs = new FileStream("file.txt", FileMode.Open))
{
    // 使用文件流
}

7字符串插值 (String Interpolation):

// 传统字符串连接
string name = "John";
int age = 30;
string message = "My name is " + name + " and I'm " + age + " years old.";

// 使用字符串插值
string name = "John";
int age = 30;
string message = $"My name is {name} and I'm {age} years old.";

猜你喜欢

转载自blog.csdn.net/qq_37335907/article/details/132115682