public class SomeClass { const int DefaultSize=100; public SomeMethod() { } } |
int number;
void MyMethod(int someNumber)
{}
|
interface ImyInterface
{…}
|
public class SomeClass
{
private int m_Number;
}
|
//正确
public class LinkedList<K,T>
{…}
//避免
public class LinkedList<KeyType,DataType>
{….}
|
using System;
using System.Collection.Generic;
using System.ComponentModel;
using System.Data;
using MyCompany;
using MyControls;
|
delegate void SomeDelegate();
public void SomeMethod()
{…}
SomeDelegate someDelegate=SomeMethod;
|
public class MyClass
{
int m_Number;
string m_Name;
public void SomeMethod1();
public void SomeMethod2();
}
|
// In MyClass.cs
public partial class MyClass
{…}
//In MyClass.Designer.cs
public partial class MyClass
{…}
|
public class MyClass
{
public const int DaysInWeek=7;
pubic readonly int Number;
public MyClass(int someValue)
{
Number=someValue;
}
}
|
using System.Diagnostics;
object GetObject()
{…}
object someObject=GetObject();
Debug.assert(someObject!=null);
|
catch(Exception exception)
{
MessageBox.Show(exception.Message);
throw;//或throw exception;
}
|
//正确
public enum Color
{
Red,Green,Blue
}
//避免
public enum Color
{
Red=1,Green=2,Blue=3
}
|
//避免
public enum Color:long
{
Red,Green,Blue
}
|
Bool IsEverythingOK()
{…}
//避免
if(IsEverythingOk())
{…}
//正确
bool ok=IsEverythingOK();
if (ok)
{…}
|
public class MyClass
{}
const int ArraySize=100;
MyClass[] array=new MyClass[ArraySize];
For (int index=0;index<array.Length;index++)
{
array[index]=new MyClass();
}
|
Dog dog=new GermanShepherd();
GermanShepherd shepherd=dog as GermanShepherd;
if (shepherd!=null)
{…}
|
Public class MyPublisher
{
MyDelegate m_SomeEvent;
Public event MyDelegate SomeEvent
{
add
{
m_SomeEvent+=value;
}
remove
{
m_SomeEvent-=value;
}
}
}
|
SomeType obj1;
ImyInterface obj2;
/*Some code to initialize obj1,then:*/
obj2=obj1 as ImyInterface;
if(obj2!=null)
{
obj2.Method1();
}
else
{
//Handle erro in expected interface
}
|
//避免
string name=””;
//正确
string name=String.Empty;
|
int number=SomeMethod();
swith(number)
{
case 1:
trace.WriteLine(“Case 1:”)
break;
case 2:
trace.Writeline(“Case 2:”);
break;
default:
debug.Assert(false);
break;
}
|
//Example of proper use of ‘this’
public class MyClass
{
public MyClass(string message)
{ }
public MyClass():this(“Hello”)
{ }
}
|
//Example of proper use of ‘base’
public class Dog
{
public Dog(string name)
{ }
virtual public void Bark(int howlong)
{ }
}
public class GermanShepherd:Dog
{
public GermanShepherd(string name):base(name)
{ }
override public void Bark(int howLong)
{
base.Bark(howLong)
}
}
|
Int CalcPower(int number,int power)
{
int result=1;
for (int count=1;count<=power;count++)
{
checked
{
result*=number;
}
}
return result;
}
|