下面的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则变为0i3 = (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、避免给枚举类型元素提供显示的值原因同上
相关文章:
c#学习记录:编写高质量代码改善整理建议1-3
c#学习记录:编写高质量代码改善整理建议9-15
以上就是c#学习记录:编写高质量代码改善整理建议4-8的详细内容。