C#编程中的66个好习惯,你有多少个?
最近在网上发现这篇文章,看看自己的编程习惯掌握了多少?
1. 避免将多个类放在一个文件里面。
2. 一个文件应该只有一个命名空间,避免将多个命名空间放在同一个文件里面。
3. 一个文件最好不要超过500行的代码(不包括机器产生的代码)。
4. 一个方法的代码长度最好不要超过25行。
5. 避免方法中有超过5个参数的情况。使用结构来传递多个参数。
6. 每行代码不要超过80个字符。
7. 不要手工的修改机器产生的代码。
a) 如果需要编辑机器产生的代码,编辑格式和风格要符合该编码标准。
b) Use partial classes whenever possible to factor out the maintained portions.
8. 避免利用注释解释显而易见的代码。
a) 代码应该可以自解释。好的代码由可读的变量和方法命名因此不需要注释。
9. Document only operational assumptions, algorithm insights and so on.
10. 避免使用方法级的文档。
a) 使用扩展的API文档说明之。
b) 只有在该方法需要被其他的开发者使用的时候才使用方法级的注释。(在C#中就是///)
11. 不要硬编码数字的值,总是使用构造函数设定其值。
12. 只有是自然结构才能直接使用const,比如一个星期的天数。
13. 避免在只读的变量上使用const。如果想实现只读,可以直接使用readonly。
public class MyClass { public readonly int Number; public MyClass(int someValue) { Number = someValue; } public const int DaysInWeek = 7; }
using System.Diagnostics; object GetObject() {…} object obj = GetObject(); Debug.Assert(obj != null);
catch(Exception exception) { MessageBox.Show(exception.Message); throw ; //和throw exception一样。 }
public class MyClass { MyClass[] array = new MyClass[100]; for(int index = 0; index < array.Length; index++) array[index] = new MyClass(); }
SomeType obj1; IMyInterface obj2; /* 假设已有代码初始化过obj1,接下来 */ obj2 = obj1 as IMyInterface; if (obj2 != null) { obj2.Method1(); } else { //处理错误 }
public class MyClass
{
public MyClass(string message )
{
}
public MyClass() : this("hello")
{
}
}
61. 除非你想重写子类中存在名称冲突的成员或者调用基类的构造函数否则不要使用base来访问基类的成员。
// 正确使用base的例子
public class Dog
{
public Dog(string name)
{}
virtual public void Bark( int howLong)
{}
}
public class GermanShepherd : Dog
{
public GermanShe pherd(string name): base (name)
{}
override public void Bark(int howLong)
{
base .Bark(howLong);
}
}
62. 基于模板的时候要实现Dispose()和Finalize()两个方法。
63. 通常情况下避免有从System.Object转换来和由System.Object转换去的代码,而使用强制转换或者as操作符替换。
class SomeClass
{}
//避免:
class MyClass <T>
{
void SomeMethod(T t)
{
object temp = t;
SomeClass obj = (SomeClass)temp;
}
}
// 正确:
class MyClass <T> where T : SomeClass
{
void SomeMethod(T t)
{
SomeClass obj = t;
}
}
64. 在一般情况下不要定影有限制符的接口。接口的限制级别通常可以用强类型来替换之。
public class Customer
{…}
//避免:
public interface IList <T> where T : Customer
{…}
//正确:
public interface ICustomerList : IList <Customer>
{…}
65. 不确定在接口内的具体方法的限制条件。
66. 总是选择使用C#内置(一般的generics)的数据结构。
[解决办法]
[解决办法]
总是选择使用C#内置(一般的generics)的数据结构。
[解决办法]
首先说一下。这个并不是什么好习惯。这个在很久之前就已经定义成为开发c#程序的标准。
[解决办法]
支持lz,lz辛苦了啊,给转发过来分享
[解决办法]
一个都没有的人飘过
[解决办法]
3. 一个文件最好不要超过500行的代码(不包括机器产生的代码)。 4. 一个方法的代码长度最好不要超过25行。
[解决办法]
不错,支持lz
[解决办法]
我是第一次看到,挺有意义的
[解决办法]
[解决办法]
6个 学习了
[解决办法]
累死
[解决办法]
我一直觉得蛮守规矩的,但是刚刚发现····貌似,不多···
[解决办法]
习惯很重要
[解决办法]
21. 避免在单个程序集里使用多个Main方法。
22. 只对外公布必要的操作,其他的则为internal。
23. Avoid friend assemblies, as it increases inter-assembly coupling.
24. Avoid code that relies on an assembly running from a particular location.
25. 使应用程序集尽量为最小化代码(EXE客户程序)。使用类库来替换包含的商务逻辑
[解决办法]
太实用了,感谢楼主啊
[解决办法]
58. 除非在不完全的switch语句中否则不要使用goto语句。
[解决办法]
非常好
[解决办法]
wincc的编程细节要注意哪些呢
[解决办法]
这个是开发一个好程序的必须标准,不是什么习惯
[解决办法]