C# - 常见问题整理

关于循环和try{}..catch{}的嵌套使用html

foreach(var item in items) {
    try {
        try{
        } catch(Exception ex) {
            throw; // 将异常抛到外层(要根据实际状况,决定是否throw)
        }    
    } catch(Exception ex) {
        continue; // or break; or return false; 视状况而定
    }
}

关于集合类的遍历操做问题前端

ConcurrentDictionary<string, string> ResDicCon = new ConcurrentDictionary<string, string>();
ResDicCon.TryAdd("0", "000"); ResDicCon.TryAdd("1", "111"); ResDicCon.TryAdd("2", "222"); ResDicCon.TryAdd("3", "333");
foreach (string key in ResDicCon.Keys) {
    string Str = null;  // ConcurrentDictionary遍历时,删除key是没问题的
    ResDicCon.TryRemove(key, out Str);
}
 
Dictionary<string, string> ResDic = new Dictionary<string, string>();
ResDic.Add("0", "000"); ResDic.Add("1", "111"); ResDic.Add("2", "222"); ResDic.Add("3", "333");
foreach (string key in ResDic.Keys) {
    // Dictionary遍历时,删除key会报错
    ResDic.Remove(key); // ResDic["2"] = "66"; 更改也会报错
}

Dictionary在foreach时,不支持删除或更改数据,不然:未处理 InvalidOperationException 集合已修改;可能没法执行枚举操做数据库

引用变量做为入参传递的问题
Dictionary<String, int>变量obj做为方法入参inPar,在方法中给inPar直接赋值,并不会影响obj的值。
由于入参inPar是obj的副本,若要影响obj的值,加上ref引用便可。后端

数组和链表初始化问题数组

int[] CntTotalArr = new int[24];  // 数组长度24,每一个元素为0
List<int> list = new List<int>(12); // 链表长度为0,最大容量为12

若要初始化列表长度,可参考以下方法浏览器

方法1:public List<int> list = new List<int>(new int[initial_size]);    
方法2:public List<int> ls = Lists.RepeatedDefault<int>(initial_size);   
public class Lists {
    public static List<T> RepeatedDefault<T>(int count) {
        return Repeated(default(T), count);
    }
    public static List<T> Repeated<T>(T value, int count) {
        List<T> ret = new List<T>(count);
        ret.AddRange(Enumerable.Repeat(value, count));
        return ret;
    }
}

文件重命名方法服务器

  • Copy + Delete
  • File.Move(srcFileName, destFileName);
  • FileInfo.MoveTo(destFileName);
  • VB.Net 中 My.Computer.FileSystem.RenameFile()
Computer MyComputer = new Computer();
MyComputer.FileSystem.RenameFile(FilePath, newFileName); 

添加引用:Microsoft.VisualBasic.dll,再加上using Microsoft.VisualBasic.Devices;网络

文件查找框架

// 查找方法1
DirectoryInfo Dir = new DirectoryInfo(directory);
FileInfo[] files = Dir.GetFiles(DateTime.Now.ToString("yyyyMMdd") + "*.xml");
// 查找方法2
string[] files = Directory.GetFiles(directory, DateTime.Now.ToString("yyyyMMdd") + "*.xml");

字符串操做ide

str.Replace("\r", "").Replace("\n", ""); 或 Regex.Replace(str, @"[\r\n]", ""); //去除换行符
Regex.Replace(str, " {2,}", ""); //多余空格

ADO.Net 与 ASP.Net
ADO.Net 是用于与数据库进行交互的面向对象类库,主要涉及:

  • SqlConnection类:链接和管理数据库连接
  • SqlCommand对象:发出针对数据库的SQL指令(增删改查)
  • SqlDataSet对象:数据在内存中的表示形式
  • SqlDataReader类:从数据库读取只进流的数据记录
  • SqlDataAdapter类:填充(fill)DataSet对象
  • SqlTransaction对象:数据库事务

ASP.Net 是.Net技术框架下的B/S(网页方向)框架技术,做为一种建立动态Web页的强大的服务器端技术,主要涉及:

  • Request对象(HttpRequest类):Page对象的成员之一,封装客户端的请求信息
  • Response对象(HttpResponse类):Page对象的成员之一,封装HTTP信息、响应客户浏览的网页
  • Cookie对象:记录客户端属性信息,存放在客户端,实现状态管理

注意,ASP.Net 不是一种语言。

VS新建各类项目的区别

//Windows程序
Windows窗体应用程序:WinForm(先后端C#)
WPF应用程序:进阶版,界面与逻辑分离(前端xaml,后端C#)
//Asp.net Web开发
ASP.Net Web应用程序:WebForm
ASP.Net MVC Web应用程序:进阶版,MVC分层解耦

[1]. WinForm .vs. WebForm

  • WinForm应用程序部署在客户端,用户经过专门为该程序打造的用户界面与其交互,WebForm应用程序部署在服务器端,用户经过浏览器与其交互
  • WinForm基于Windows桌面应用程序窗体,WebForm基于Web浏览器的网络应用程序窗体
  • WinForm是窗体模式,WebForm是浏览器模式

详情参见:关于ASP.NET WebForm与ASP.NET MVC的比较
[2]. WebForm .vs. MVC
二者均是ASP.Net Web应用程序开发的技术,基于ASP.Net,更深一层是基于.Net Framework。
WebForm支持控件拖拽,但存在问题

  • ViewState,页面重
  • 页面生命周期
  • html受限

详情参见:Why MVC is Better?

枚举enum

Enum.GetNames(typeof(EnumName)).Length #枚举类中元素个数
(int)返回数值,.ToString()直接返回字段名

文件读写
FileStream fs = new FileStream(url, FileMode.Open, FileAccess.Read);
提示报错:文件正由另外一进程使用,所以该进程没法访问此文件。
缘由:考虑文件可能有读写操做,只读方式须搭配共享锁
解决:FileStream fs = new FileStream(url, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
详情参见:FileShare

控制winform窗口按钮方法
方法1:this.ControlBox = false; 可是会一块儿控制最大、最小、关闭按钮
方法2:能够单独控制关闭按钮

private const int CP_NOCLOSE_BUTTON = 0x200;
protected override CreateParams CreateParams {
    get {
        CreateParams myCp = base.CreateParams;
        myCp.ClassStyle = myCp.ClassStyle | CP_NOCLOSE_BUTTON;
        return myCp;
    }
}

方法3:设置关闭按钮点击失效,须kill进程

this.FormClosing += new FormClosingEventHandler(FormClosingSelf);
private void FormClosingSelf(object sender, FormClosingEventArgs e)
{
    this.WindowState = FormWindowState.Minimized;
    e.Cancel = true;
}

具体参见:窗体按钮显示控制方法简谈

相关文章
相关标签/搜索