推荐区看到《大家晒下java开发代码的小技巧啊!》
突发奇想,搞个C#版的和它PK下。
抛砖引玉:1. 使用as,而非isobject o = GetFromCache("A_KEY");
EmployeeInfo employee = o as EmployeeInfo;
if(employee != null) {
// TODO: 代码
}
2. 使用DataReader读取数据using(SqlDataReader reader = SqlHelper.ExecuteReader(cmd)) {
while(reader.read()) {
// TODO: 读取当前行的数据
}
}
3. 尽量使用强类型集合(包括泛型集合),而非DataTableusing(SqlDataReader reader = SqlHelper.ExecuteReader(cmd)) {
Ilist<EmployeeInfo> list = new List<EmployeeInfo>();
while(reader.read()) {
list.add(new EmployeeInfo(
reader.getInt32(0)
// 其它字段
));
}
}
4. 使用StringBuilder操作频繁变动的字符串,但以下情况例外 string s = "str1" + "str2" + "str3" + "str4"; // 这段代码不需要使用StringBuilder,因为编译后的代码为 string s = "str1str2str3str4";
突发奇想,搞个C#版的和它PK下。
抛砖引玉:1. 使用as,而非isobject o = GetFromCache("A_KEY");
EmployeeInfo employee = o as EmployeeInfo;
if(employee != null) {
// TODO: 代码
}
2. 使用DataReader读取数据using(SqlDataReader reader = SqlHelper.ExecuteReader(cmd)) {
while(reader.read()) {
// TODO: 读取当前行的数据
}
}
3. 尽量使用强类型集合(包括泛型集合),而非DataTableusing(SqlDataReader reader = SqlHelper.ExecuteReader(cmd)) {
Ilist<EmployeeInfo> list = new List<EmployeeInfo>();
while(reader.read()) {
list.add(new EmployeeInfo(
reader.getInt32(0)
// 其它字段
));
}
}
4. 使用StringBuilder操作频繁变动的字符串,但以下情况例外 string s = "str1" + "str2" + "str3" + "str4"; // 这段代码不需要使用StringBuilder,因为编译后的代码为 string s = "str1str2str3str4";
解决方案 »
- 如何获取图片内的文字信息?
- 如何知道用户PC机上是否安装了Service Pack 1 for .NET Framework 2.0?
- 怎样在.NET中执行SQL语句,并把结果查返回显示在WEB面面中
- 对我来说的超级大难题,挂起当前运行的进程,世纪问题
- 利用sql数据库生成的脚本文件,能保存各表中的关系不
- 请问如何列出(生成一个txt文件)(或某一folder)下面每个folder占用的磁盘空间?
- 请问哪里有.net 的最新中文版下载?地址要正确
- 搭建oauth2.0服务端
- 在C#winform 中,如何遍历当前窗体中的全部textbox控件
- Gzipstream使用中出现问题,GZip 头中的幻数不正确。附源码。
- C#中的定制特性功能到底有什么用处?
- serialPort类的ReadExisting()方法串口读取GPS数据,为何得到一堆乱码?
{
public static void SendTabKey(this Control control, Keys key)
{
if (key == Keys.Enter)
SendKeys.Send("{TAB}");
}
}
{
foreach (Control cc in c.Controls)
{
if (cc.GetType() != typeof(Panel))
{
PanelClear(cc);
}
else
{
((Panel)cc).Visible = false;
}
}
}
2)使用Enum代替奇迹数先说两点。想起来再加。
{
if (Application.OpenForms[j].Name.Equals("FNO31000"))
{
fno3100 = true;
}
}
If (fno3100 = true)
FNO31000 fno = (FNO31000)Application.OpenForms["FNO31000"]
String.Format("{0}{1}{2}{3}", str0, str1, str2, str3);
{
dataGridView1.Rows[i].Cells[str].ReadOnly = true;
DataGridViewCell cell = new DataGridViewTextBoxCell();
cell.Style.BackColor = Color.Wheat;
//cell.ReadOnly = true;
cell.Value = "N";
cell.Style.BackColor = Color.White;
dataGridView1.Rows[i].Cells[str] = cell;
dataGridView1.Rows[i].Cells[str].Style.ForeColor = Color.White;
dataGridView1.Rows[i].Cells[str].Style.SelectionBackColor = Color.White;
dataGridView1.Rows[i].Cells[str].Style.SelectionForeColor = Color.White;
}
p.StartInfo.FileName = "cmd.exe"; //设定程序名
p.StartInfo.UseShellExecute = false; //关 ?Shell的使用
p.StartInfo.RedirectStandardInput = true; //重定向标 ã输 ¤J
p.StartInfo.RedirectStandardOutput = true; //重定向标 ã输 ¥X
p.StartInfo.RedirectStandardError = true; //重定向错 ?输 ¥X
p.StartInfo.CreateNoWindow = true; //设置不显 ¥Ü窗口
p.StartInfo.WorkingDirectory = @"E:\";
p.Start(); //启 ?
p.StandardInput.WriteLine("新增文字文件.bat");
p.StandardInput.WriteLine("exit");
就贴这么多把
字符串留用技术用来处理大量的字符串,而这些字符串中又会有许多重复的字符,例如:
"str1", "str2", ... , "str100" 共10,000个这样的字符,毫无疑问,其实就99个字符
这种情况可以使用到字符串留用技术,会提到性能2. 数组永远是0基的3. 使用多线程或异步操作的时候使用线程池的QueueUserWorkItem()方法将需要执行的任务排队,而不是手动去Start一个线程
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
public delegate bool DelegateTest(object obj1, object obj2);
class Class1
{
static void Main()
{
Employee[] Employees =
{
new Employee("huguo",1000000),
new Employee("lili",20000),
new Employee("lulu",30000),
new Employee("xixi",50000),
new Employee("jianjian",10000),
new Employee("yoyo",9000)
};
//委托DelegateTest代理的方法是Greate
DelegateTest MyTest = new DelegateTest(Employee.Greate);
Sorter MySort = new Sorter();
//冒泡算法中第一个参数是对应Employees数组信息,第二个参数是委托
MySort.Sort(Employees, MyTest);
for (int m = 0; m < Employees.Length; m++)
{
Console.WriteLine(Employees[m].ToString());
}
}
}
class Employee
{
public string Name;
public int Salary;
public Employee(string Name, int Salary)
{
this.Name = Name;
this.Salary = Salary;
}
//用override重写string方法
public override string ToString()
{
return string.Format(Name + ",{0:C},", Salary);
}
//定义一个方法,如果obj2传过来的 Salary大于obj1就返回true;
public static bool Greate(object obj1, object obj2)
{
Employee Employee1 = (Employee)obj1;
Employee Employee2 = (Employee)obj2;
return (Employee2.Salary > Employee1.Salary) ? true : false;
}
}
class Sorter
{
public void Sort(object[] ArrayObj, DelegateTest Test)
{
//下面就是冒泡算法啦
for (int i = 0; i < ArrayObj.Length; i++)
{
for (int j = i + 1; j < ArrayObj.Length; j++)
{
if (Test(ArrayObj[j], ArrayObj[i]))
{
object Temp = ArrayObj[i];
ArrayObj[i] = ArrayObj[j];
ArrayObj[j] = Temp;
}
}
}
}
}
}
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/ws_hgo/archive/2009/07/25/4380283.aspx
{
if(!Page.IsPostBack)
{
CreateNum();
}
}
//在从1到20间随机生成6个互不相同的整数。
public void CreateNum()
{
ArrayList MyArray = new ArrayList();
Random random = new Random();
string str = null;
//循环的次数
int Nums = 6;
while (Nums > 0)
{
int i = random.Next(1, 9);
if (!MyArray.Contains(i))
{
if (MyArray.Count < 6)
{
MyArray.Add(i);
}
}
Nums -= 1;
}
for (int j = 0; j <= MyArray.Count - 1; j++)
{
str += MyArray[j].ToString();
}
Response.Write(str);
}
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/ws_hgo/archive/2009/05/09/4164277.aspx
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
ReplaceStr();
}
}
public void ReplaceStr()
{
ArrayList MyArray = new ArrayList();
MyArray.Add("123");
MyArray.Add("aaa");
if (MyArray.Contains("aaa"))
{
MyArray.Remove("aaa");
MyArray.Add("bbb");
}
for (int i = 0; i <= MyArray.Count - 1; i++)
{
Response.Write(MyArray[i].ToString());
}
}
//方法2
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
ReplaceStr();
}
}
public void ReplaceStr()
{
string [] tm = new string[] { "123", "aaa" };
for (int i = 0; i < tm.Length; i++)
{
if (tm[i].ToString() == "aaa")
{
tm[i]=tm[i].Replace("aaa", "bbb");
}
}
for (int i = 0; i <= tm.Length - 1; i++)
{
Response.Write(tm[i].ToString());
}
}
//方法3
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
string[] tm = new string[] { "123", "aaa" };
string Array=ReplaceValue(tm, "aaa", "bbb", ",");
Response.Write(Array);
}
}
public static string ReplaceValue(string[] item, string oldSv, string newSv, string separator)
{
if (item == null) return string.Empty;
StringBuilder sb = new StringBuilder();
foreach (string s in item)
{
if (s == oldSv)
{
sb.Append(newSv);
sb.Append(separator);
}
else
{
sb.Append(s);
sb.Append(separator);
}
}
string returnstr = sb.ToString();
returnstr = (returnstr.EndsWith(separator)) ? returnstr.Substring(0, returnstr.Length - 1) : returnstr;
return returnstr;
} 本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/ws_hgo/archive/2009/05/10/4164995.aspx
private static void PrepareCommand(MySqlConnection con,MySqlCommand mycmd,string cmdText,MySqlParameter[] cmdParams,CommandType cmdType)
{
con.Open();
mycmd.Connection = con;
mycmd.CommandText = cmdText;
mycmd.CommandType = cmdType;
if (cmdParams != null)
{
foreach (MySqlParameter param in cmdParams)
{
//if((param.Direction==ParameterDirection.InputOutput || param.Direction==ParameterDirection.Input) && (param.Value==null))
//{
// param.Value = DBNull.Value;
mycmd.Parameters.Add(param);
//}
}
}
}
楼上用MySql?
本人很喜欢MySql!
SqlDataReader持久占连接。
而且DataSet对VS控件的兼容性更强一些。
推荐使用using(){}
去写实现了IDisposable的对象
非常漂亮!
//尽量不用
string str="";
//而是
string str=string.Empty;
DataSet过于强大
但是,强大是要付出代价的,哈哈
其实,DataTable内部就是用了SqlDataReader(本人98%肯定)
一般情况下,这个问题基本上不用考虑。
但是上升到公共类库,就需要考虑语言的互操作性
也就是CLR的兼容性
如果我没有记错的话:
Catch(Exception) 只捕捉符合公共语言运行库的异常
Catch{} 则可以捕捉所有类型的异常
释放连接后,DataTable是能够使用的啊,难道从头迭代到末尾了?
还是不太同意
我坚持
仅仅在需要的时候重写ToString()方法
条款2:运行时常量(readonly)优于编译时常量(const)
条款3:操作符is或as优于强制转型
条款4:使用Conditional特性代替#if条件编译
条款5:总是提供ToString()方法
条款6:明辨值类型和引用类型的使用场合
条款7:将值类型尽可能实现为具有常量性和原子性的类型
条款8:确保0为值类型的有效状态
条款9:理解几个相等判断之间的关系
条款10:理解GetHashCode()方法的缺陷
条款11:优先采用foreach循环语句
条款12:变量初始化器优于赋值语句
条款13:使用静态构造器初始化静态类成员
条款14:利用构造器链
条款15:利用using和try/finally语句来清理资源
条款16:尽量减少内存垃圾
条款17:尽量减少装箱与拆箱
条款18:实现标准Dispose模式
条款19:定义并实现接口优于继承类型
条款20:明辨接口实现和虚方法重写
条款21:使用委托表达回调
条款22:使用事件定义外发接口
条款23:避免返回内部类对象的引用
条款24:声明式编程优于命令式编程
条款25:尽可能将类型实现为可序列化的类型
条款26:使用IComparable和IComparer接口实现排序关系
条款27:避免ICloneable接口
条款28:避免强制转换操作符
条款29:只有当新版基类导致问题时才考虑使用new修饰符
条款30:尽可能实现CLS兼容的程序集
条款31:尽可能实现短小简洁的函数
条款32:尽可能实现小尺寸、高内聚的程序集
条款33:限制类型的可见性
条款34:创建大粒度的Web API
条款35:重写优于事件处理器
条款36:合理使用.NET运行时诊断
条款37:使用标准配置机制
条款38:定制和支持数据绑定
条款39:使用.NET验证
条款40:根据需要选用恰当的集合
条款41:DataSet优于自定义结构
条款42:利用特性简化反射
条款43:避免过度使用反射
条款44:为应用程序创建特定的异常类
条款45:优先选择强异常安全保证
条款46:最小化互操作
条款47:优先选择安全代码
条款48:掌握相关工具与资源
条款49:为C# 2.0做准备
条款50:了解ECMA标准
数据库要建立索引、使用事务。
ASP.NET合理利用母版页和缓存。
提取字符串注意正则表达式的优化,提高准确性来减少迭代。
算术表达式要多用小括号。
private bool test = false;if(test){;}
结构简单时使用三目运算符。
灵活使用switch。
平时写的代码要OOP,然后封装成自己的类库,提高日后开发效率。
多用组合,少用继承。
字符串合理使用Trim()。
实现文件复制时,尽量减少对磁盘读写次数。
正是因为DataTable的强大所以才不推荐使用它(不是不能)
考虑下面的代码:DataTable GetEmployee1() {
return table;
}
Ilist<EmployeeInfo> GetEmployee2() {
return list;
}void InitInterfaceUsingDataTable() {
DataRow row = GetEmployee1().rows[0];
this.txName = row["EmployeeName"]; // 你确定字段名是EmployeeName吗?
}
void InitInterfaveUsingList() {
EmployeeInfo> employee = GetEmployee2()[0];
this.txName = list.EmployeeName; // 这样写代码很舒服
}
// 再考虑下下下面的情况
// 某天,老板对你说:“嘿,去把EmployeeName改成EmployeeFirstName”
contains代替indexof
字符串组合使用StringBuilder,减少字符串拷贝使用接口来编程
使用属性代替原始数据
as 和 is 并不矛盾,一个是转换类型,一个是判断类型
public enum ProcessAccessType
{
PROCESS_TERMINATE = (0x0001),
PROCESS_CREATE_THREAD = (0x0002),
PROCESS_SET_SESSIONID = (0x0004),
PROCESS_VM_OPERATION = (0x0008),
PROCESS_VM_READ = (0x0010),
PROCESS_VM_WRITE = (0x0020),
PROCESS_DUP_HANDLE = (0x0040),
PROCESS_CREATE_PROCESS = (0x0080),
PROCESS_SET_QUOTA = (0x0100),
PROCESS_SET_INFORMATION = (0x0200),
PROCESS_QUERY_INFORMATION = (0x0400)
}
[DllImport("kernel32.dll")]
public static extern IntPtr OpenProcess(UInt32 dwDesiredAccess, Int32 bInheritHandle, UInt32 dwProcessId);
[DllImport("kernel32.dll")]
public static extern Int32 CloseHandle(IntPtr hObject);
[DllImport("kernel32.dll")]
public static extern Int32 ReadProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, [In, Out] byte[] buffer, UInt32 size, out IntPtr lpNumberOfBytesRead);
[DllImport("kernel32.dll")]
public static extern Int32 WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, [In, Out] byte[] buffer, UInt32 size, out IntPtr lpNumberOfBytesWritten); 打开进程private IntPtr m_hProcess = IntPtr.Zero; //这个保存打开了个进程句柄 public void OpenProcess()
{
// m_hProcess = ProcessMemoryReaderApi.OpenProcess(ProcessMemoryReaderApi.PROCESS_VM_READ, 1, (uint)m_ReadProcess.Id);
ProcessMemoryReaderApi.ProcessAccessType access;
access = ProcessMemoryReaderApi.ProcessAccessType.PROCESS_VM_READ
| ProcessMemoryReaderApi.ProcessAccessType.PROCESS_VM_WRITE
| ProcessMemoryReaderApi.ProcessAccessType.PROCESS_VM_OPERATION;
m_hProcess = ProcessMemoryReaderApi.OpenProcess((uint)access, 1, (uint)m_ReadProcess.Id);
}m_ReadProcess.Id 进程的ID编号 读取 public byte[] ReadProcessMemory(IntPtr MemoryAddress, uint bytesToRead, out int bytesRead)
{
byte[] buffer = new byte[bytesToRead]; IntPtr ptrBytesRead;
ProcessMemoryReaderApi.ReadProcessMemory(m_hProcess, MemoryAddress, buffer, bytesToRead, out ptrBytesRead); bytesRead = ptrBytesRead.ToInt32(); return buffer;
}IntPrt MemoryAddress 为要读取的内存地址uint bytesToRead 需要读的数量out int bytesRead 实际读出的数量 写入 public void WriteProcessMemory(IntPtr MemoryAddress, byte[] bytesToWrite, out int bytesWritten)
{
IntPtr ptrBytesWritten;
ProcessMemoryReaderApi.WriteProcessMemory(m_hProcess, MemoryAddress, bytesToWrite, (uint)bytesToWrite.Length, out ptrBytesWritten); bytesWritten = ptrBytesWritten.ToInt32();
}IntPrt MemoryAddress 为要读取的内存地址byte[] bytesToWrite 需要写入的数据out int bytesWritten 实际写入多少
现在我做了图片移动的程序,时间触发每五分中遍历一次文件目录,但是现在有个问题,但文件目录图片很多的时候,五分钟没法遍历完文件目录,这样就会造成程序没法工作了。请问各位高人,这种问题大家是如何解决?可否之间迷津,谢谢!小段代码如下:
public void CopyDir(string srcPath, string aimPath)
{
try
{
// 检查目标目录是否以目录分割字符结束如果不是则添加之
if (aimPath[aimPath.Length - 1] != Path.DirectorySeparatorChar)
aimPath += Path.DirectorySeparatorChar;
// 判断目标目录是否存在如果不存在则新建之
if (!Directory.Exists(aimPath)) Directory.CreateDirectory(aimPath);
// 得到源目录的文件列表,该里面是包含文件以及目录路径的一个数组
// 如果你指向copy目标文件下面的文件而不包含目录请使用下面的方法
//string[] fileList = Directory.GetFiles(srcPath,"*.BMP");
string[] fileList = Directory.GetFileSystemEntries(srcPath); // 遍历所有的文件和目录
foreach (string file in fileList)
{
// 先当作目录处理如果存在这个目录就递归Copy该目录下面的文件
if (Directory.Exists(file))
{
DirectoryInfo di = new DirectoryInfo(file); if (di.Name.Substring(di.Name.LastIndexOf(" D") + 1) == "DATA FILE" || di.Name.Substring(di.Name.LastIndexOf("t") + 1) == " images" ||di.Name.Substring(di.Name.LastIndexOf("t") + 1) == " image") CopyDir(file, aimPath + Path.GetFileName(file));
//System.Threading.Thread.Sleep(500);
//DeleteOriDir(srcPath + Path.GetFileName(file));
cpend = "goings";
}
// 否则直接Copy文件
else
{ FileInfo fi = new FileInfo(file);
TimeSpan span = DateTime.Now.Subtract(fi.CreationTime);
//MessageBox.Show(fi.Extension ); if (span.TotalMinutes > 5 && fi.Extension == ".BMP" && fi.Name.Substring(0, 3) != "000")
{
Bitmap myBitmap = new Bitmap(file);
//生成80*100的缩略图
//Image myThumbnail = myBitmap.GetThumbnailImage(1280,1024,null,IntPtr.Zero);
myBitmap.Save(aimPath + Path.GetFileName(file), System.Drawing.Imaging.ImageFormat.Jpeg);
myBitmap.Dispose();
//myThumbnail.Save(aimPath + Path.GetFileName(file));
//File.Move(file, aimPath + Path.GetFileName(file));
//File.Copy(file, aimPath + Path.GetFileName(file),true);
//删除图片文件
File.Delete(srcPath + Path.GetFileName(file));
cpend = "goings";
} //
//MessageBox.Show(fi.Name);
}
}
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
//cpend = "completed";
}
/// override 系统的Equals函数
/// </summary>
/// <param name="obj"></param>
/// <returns>返回是否相等</returns>
public override Boolean Equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (GetType() != obj.GetType())
return false;
aprResult other = (aprResult)obj;
if (this.numA == other.numA && this.numB == other.numB) return true;
return false;
} /// <summary>
/// 重载系统的GetHashCode函数
/// </summary>
/// <returns>返回hashcode</returns>
public override int GetHashCode()
{
int PRIME = 31;
int result = 1;
result = PRIME * result + ((numA == 0) ? 0 : numA.GetHashCode());
return result;
}aprResult 是我的一个类,以上方法是为了重载contains方法。