【读书笔记】编写高质量代码改善C# 建议4-8

4、TryParse比Parse好

下面的TryParse的方法定义

public static bool TryParse(string s, out Double result);

Parse如果转换失败会报错,但是TryParse有返回值可以判断是否转换成功

string str1 = "abfc12";
if(double.TryParse(str1, out double dou1))
{
    Console.WriteLine(dou1);
}

5、建议使用int? 来确保值类型也可以为null

如果有需要值类型为空,我们可能会使用一个特殊值例如 -1 来判断int是不是为空,最好改成int?类型,判断是否为null

Nullable<int> i1 = 4;
// i2 和 i1 的定义方式一样 只是写法不同 下面的int?是一个语法糖
int? i2 = null;
int i3 = 0;
//int类型可以默认转为int?类型
i2 = i3;
//int?类型需要强转成int类型,如果是null则变为0
i3 = (int)i2;

6、区别readonly和const的使用方法

简单区别就是const效率高,readonly灵活性高

const是编译器常量,readonly是运行时常量

const int constNum = 1;
public string name;
public int age;
public FirstType()
{
    name = "aa";
    age = constNum;
    age = 1;
}
//使用以上代码测试,下面的编译成的IL代码
  IL_0000:  ldarg.0
  IL_0001:  call       instance void [mscorlib]System.Object::.ctor()
  IL_0006:  nop
  IL_0007:  nop
  IL_0008:  ldarg.0
  IL_0009:  ldstr      "aa"
  IL_000e:  stfld      string CSharpSuggest.FirstType::name
  IL_0013:  ldarg.0
  IL_0014:  ldc.i4.1
  IL_0015:  stfld      int32 CSharpSuggest.FirstType::age
  IL_001a:  ldarg.0
  IL_001b:  ldc.i4.1
  IL_001c:  stfld      int32 CSharpSuggest.FirstType::age
  IL_0021:  ret

可以看出13,14,15   和 1a,1b,1c是一样的,所以 age = constNum;和 age = 1;是等效的 所以效率最高

const只能修饰基元类型、枚举类型或字符串类型,readonly则没有限制

const天然是static 不能再增加static

readonly的值一般在构造函数里面赋值,每一个类的对象都可以拥有不同的readonly值,但由于const是静态的,所以所有的类该值都是一样的

书中有上面这一句话,我一直有个疑问,在类内赋值和构造函数赋值有什么区别,网上没搜到,反编译出来的IL代码仅仅是变量定义的顺序区别,如果有知道请告知。。

7、将0作为枚举的默认值

我理解的是如非必要,不要更改枚举的数值,可能会出现意料之外的结果

8、避免给枚举类型元素提供显示的值

原因同上

猜你喜欢

转载自blog.csdn.net/qq_33413868/article/details/81430006