1、代码问题:
以前我总是这样写代码:
//m_isSomeEvent:bool
if(m_isSomeEvent){
m_isSomeEvent = false;
}else{
m_isSomeEvent = true;
}
后来这样写:
m_isSomeEvent = m_isSomeEvent?false:true;
再后来这样写:
m_isSomeEvent = !m_isSomeEvent;
类似的有:
if(this.m_button.Text==i_someString){
this.m_button.Enabled = true;
}else{
this.m_button.Enabled = false;
}
后来就写成:
this.m_button.Enabled = this.m_button.Text == i_someString;
有什么区别吗?没有,只能说我是越来越懒了。
字符串问题:
以前总是这样写:
string m_path = "c:\test\" "MyFolder" "\someFile.dat";
后来会这样写:
string m_path = string.Format("{0}\{1}\{2}",i_drive,i_path,i_file);
再后来这样写:
string m_path = Path.Combine(Path.Combine(i_drive,i_path),i_file);
虽然有点麻烦,但比起因为路径出错而造成的麻烦,这算不了什么。
还有就是,以前这样写:
string m_filePath = ".myFile.dat"; //在程序正在运行的目录里取文件。
后来这样写:
string m_filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,"myFile.dat");
理由就不用说了,安全第一。
还有一个就是:
string m_fullPath = "c:\test1\test2\file.dat";
//Some code withe the path to create the file.
后来总要这样:
string m_fullPath = "c:\test1\test2\file.dat";
if(!Directory.Exists(Path.GetDirectoryName(m_fullPath)))
{
Directory.CreateDirectory(Path.GetDirectoryName(m_fullPath));
}
//Some code withe the path to create the file.
再后来:
string m_fullPath = "c:\test1\test2\file.dat";
if(!Directory.Exists(Path.GetDirectoryName(m_fullPath)))
{
try{
Directory.CreateDirectory(Path.GetDirectoryName(m_fullPath));
}
catch(Exception ex)
{
MessageBox.Show(this,"Error! Object folder " m_fullPath " does't exist. And cann't create this folder. Message:" ex.Message);
}
}
//Some code withe the path to create the file.
代码虽然越来越多,但安全性却是越来越高。总之,代码能省的地方就该省,不能省的,一个也不能少。
还有这样的问题:
以前这样写函数:
public void SomeFunction(object i_someObject){
//
}
后来一般情况我都会先选择这样的代码:
public void SomeFunction(ref object i_someObject){
//
}
还有一个小问题,就是我喜欢在所有的成员使用上加上this,因为这样可以直接知道它是成员还是函数内的局部变量。
2、再讨论一个try-catch结结构:
以前这样写:
模块A中的某函数:
public object SomeFunction(ref object i_someParameter){
SomeObject m_tempObject = new SomeObject(); //m_tempObect need release after use it.
object m_result = null;
//Some code with SomeObject m_tempObject;
m_tempObject.Dispose();
return m_result;
}//模块B中的调用:
object m_myObject = SomeFunction(ref m_somePar);
评论加载中…
![]() |