Home >Backend Development >C#.Net Tutorial >C# learning record: Writing high-quality code and improving organization suggestions 1-3
Suggestion 1: Use strings correctly
string str1 = "str1" + 9; string str2 = "str2" + 9.ToString();
The first line of code will generate a boxing and a string The concat
and the second line of code uses ToString(), which uses Number.FormatInt32
internally. Its prototype is
NumberFormatInt32 is an unmanaged method, and its operating efficiency is much higher than that of normal c# managed code, so the efficiency of the second line of code is higher than that of the first line
As for what is managed code and unmanaged code, I Quoting a passage from another blog:
Managed code and unmanaged codeAs we all know, the high-level languages we use for normal programming cannot recognized by the computer. High-level language needs to be translated into machine language before it can be understood and run by the machine. |
简单理解就是托管代码加了一个中间层,使其可以跨平台,不过效率会降低,而非托管代码就不会产生这样的情况
所以我们编写代码秉承一个原则:尽量减少装箱拆箱
StringBuilder的效率来源于预先以非托管的方式分配内存,如果没有预先定义长度,默认长度为16,不够的时候会重新分配内存,依次加16的倍数,所以如果你提前知道字符串需要的最大长度,最好预先定义好,这样就不会频繁分配内存从而带来效率的降低
2、使用默认转型方法
这个建议的大体内容是尽量使用系统所带的转换类型的方法
例如 int.Parse ToString() System.Convert 等等
两个类型之间转换有两种情况
1. 他们是父子类的关系: ChildType = (ChildType)ParentType
2.没有继承关系,或者继承同一个父类,这时候就需要重写强转方法
class FirstType { public string Name { get; set; } } class SecondType { public string Name { get; set; } public static explicit operator SecondType(FirstType firstType) { SecondType secondType = new SecondType() { Name = firstType.Name }; return secondType; } } FirstType firstType = new FirstType() { Name = "张" }; SecondType secondType = (SecondType)firstType;
如果是继承的关系,为了效率推荐使用 ChildType = ParentType as ChildType
这个就更上面提到的,尽量使用系统方法的转换,而不是强制转换
我写Unity的时候有这样一个需求,右键点击装备的时候会使用,装备有Equipment,Weapon,我们需要判断是Equipment还是Weapon类型,它们都是继承Item类型,有两种方法可用:
Weapon weapon = item as Weapon; if(weapon != null) { //TODO 使用武器 } if(item is Weapon) { weapon weapon = item as Weapon; //TODO 使用武器 }
第一种方法只判断了一次类型,而第二种方法判断了两次类型
书上说as不能判断基元类型,但是经过我的测试发现书上写错了,as仅仅不能判断值类型,这里大家可以自己测试一下
相关文章:
The above is the detailed content of C# learning record: Writing high-quality code and improving organization suggestions 1-3. For more information, please follow other related articles on the PHP Chinese website!