const和readonly
1、resharper提示当参数为List时,可以改为IEnumerable<T>,因为:
If you have a method whose parameter is an array, a List or some other type that implements IEnumerable<T>, ReSharper will offer you an option to change the parameter type accordingly – provided, of course, that the method itself only iterates the collection and does not access any non-IEnumerable members.
The benefit from this change, if you choose to make it, is that the method becomes agnostic with respect to the type of collection you give it.
意思是:这样传入参数可以是实现了IEnumberable<T>接口的任意类型,比如list,数组或其他。
2、const和readonly
在外出时利用间隙时间看了下effective c#。
const是编译时变量,readonly是编译时变量。两者区别如下:
前者效率稍高,但可伸缩性不如后者。
前者在编译成IL时就已经确定值了,运行时就和常量一样;后者则在运行时才得到值。
const适合永远不变的常量。
readonly适合在某些场景会变化的常量。
const只能是值类型、结构和字符串,永远不能用new来给const修饰的常量赋值,即便是new 一个值类型,如Date
readonly则可以是任何类型。