C#學習筆記(零碎知識點收集)

來源:互聯網
上載者:User

類注釋用 ///

錯誤資訊可直接 Ctrl+C

#region
#endregion 摺疊

輸入Cw兩次按Tab可快速得到Console.WriteLine();

Console.WriteLine("{0}的年齡是{1},學曆是{2}",name,age,edu);

Convert.ToString(163); Convert.ToInt32("78");
類型轉換

Console.Clear(); 清屏

out ref
使用者向調用函數傳值,out、ref關鍵詞兩邊都得有

if(str1.Equals(str2)) if(str1.Equals(str2,StringComparison.OrdinalIgnoreCase))
字串比較

if(str1.ToUpper().Equals(str2.ToUpper())) str.ToLower()
字串大小寫轉換

所有的對象執行個體都可以掉用.ToString()方法

str.SubString(6,3) str.Contains("自由")
str.Split(' ') str.Split(' ','-','/')
可為字元、字串、字元數組等

str.StartWith("kai") str.EndWith("jin")
int n = "Hello,World!".IndexOf("wo",3)
3為起始位置。不包含則返回-1

-----------------------------------------------------------------------

select count(*) from T_Person;
select max(salary) from T_Person;
select min(salary) from T_Person;
select avg/sum(salary) from T_Person;

select * from T_Person order by age ASC/DESC;
升序、降序
select * from T_Person order by age DESC,salary ASC;

select * from T_Person where salary>5000 order by age DESC;
where在order by前

select * from T_Person where name Like '_kai' or name Like '%kai%'
萬用字元:_單個字元、%多個字元 

where age between 20 and 30

select age count(*) from T_Person group by age;

select age,max(salary),count(*) from T_Person group by age

除了彙總函式外
select age,count(*) from T_Person group by age Having count(*)>1
having對分組後的資料進行過濾

select top 3 *from T_Person order by salary DESC
top關鍵詞用於選擇前N個

select top 3 *from T_Person where Fnumber not in (select top 5 Fnumber from T_Person order by salary DESC)order by salary DESC;
不在前五中的前三,也就是第6-8名 不在前五
前五

alter Table T_Person add company varchar(20);
新增加一個欄位

select distinct department from T_Person; 排除重複項
select distinct department,company from T_Person;
distinct針對整行排除重複,並非只針對department

select name,age from T_Person
Union union聯合
聯合結果類 合并重複項
select name,age from T_employee; 欄位數量要一致,類型要相容(相同最好)可以不同

select number,salary from T_Person
union all
select '合計',sum(salary) from T_Person; union all 補全欄位已相同

ABS()求絕對值 Ceiling()舍入到最大整數
Floor()舍入到最小整數 Round()四捨五入

Len()求字串長度 Lower()
Upper() LTrim()
RTrim() 去空格
沒有trim()  substring(string,startposition,length)

-----------------------------------------------------------------------

enum color 枚舉
{ Red,
Yellow,
Blue, Green=5,
White} 那麼Red=0  Yellow=0  Blue=0  Green=5  White=6 賦值的後面自動遞增

二維數組
int[,] a = new int[,]{{1,1},{2,2},{3,3}};
不規則數組,必須對各子數組進行初始化, 訪問時用a[x][y]
int[][] a = new int[3][];
a[0] = new int[]{1};
a[1] = new int[]{1,2};
a[2] = new int[]{1,2,3};

string str1 = "C:\\a\\b.txt"; string str2 = @"C:\a\b.txt";
@符號表示忽略逸出字元的分隔字元,str1和str2完全相同

string str = "Hello";
Console.WriteLine(String.Copy(str)+str.SubString(3,2)+str.Insert(3,"*****"));
結果分別是對str的複製,sub,插入:
Hello lo
Hel****lo

int num = int.Parse(Console.ReadLine()); int num = Convert.ToInt32(Console.ReadLine());

char[] c = Console.ReadLine().ToCharArray();
字元比較 if(char[0]>='0' && char[0]<='9')
if(char[0]>='a' && char[0]<='z')

switch(運算式) //可為整數類型和字串類型
{ case 1: -----; break;
case 2: -----; break;
default: ------; break;  //break必須有!不可穿透。 default可有可無
}

foreach(string name in new string[]{"gukai","guxiaofei","luyong"})
{} 不用考慮數組下標越界

main方法中用return則程式結束

params數組型參數
public int drink(int id,params string[] name) {} 
1 調用的時候用 int kk = drink(33,"gu","fu","lu");
或者string[] aa = {"aa","bb","cc"}drink(33,aa);
長度可變
2 一個方法中只能聲明一個params參數
3 params參數必須在所有參數之後
4 必須為一位元組
5 不能同時使用out和ref關鍵詞

索引器--------------------------有待學習

-----------------------------------------------------------------------

SqlConnection conn = new SqlConnection("Database='hrms';Data Source='192.168.4.160';User Id='root';Password='dada7020';charset='utf8';pooling=true");
SqlCommand cmd = conn.CreateCommand()

SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = cmdText;

SqlDataReader reader = cm.ExecuteReader();
while(reader.Read()) {
}

conn.Open(); conn.Close();
conn.Dispose(); 用using最方便。
出了using範圍後調用dispose,並判斷是否close了,using語句自動先close再dispose

SQL 注入漏洞攻擊 ------where password = 'kai' or '1'='1';

需參數化查詢 cmd.CommandText = "select * from where name = @name and password = @password";
cmd.Paraneters.Add(new SqlParaneters("@name",name));
cmd.Paraneters.Add(new SqlParaneters("@password",password);
MySql中用?做參數化查詢的標記

winform中
this.AcceptButton = button1; this.CancelButton = button2;

NumericUpDown 控制項 numericUpDown1.Maximun = 25;
numericUpDown1.DecimalPlaces = 2;

SqlServer
getDate()獲得當前日期 DateAdd(datepart,number,date)
參數分別為計量單位、數值,日期 datepart 可以為year\month\day\hh\yy等
DATEADD(MONTH,-8,getDate())當前日期向前8個月 DateDiff(datepart,startdate,enddate)計算日期的差值

select DateDiff(year,FinDate,getDate()),count(*) from T_Person group by DateDiff(year,FinDate,getDate());

cast類型轉換
select Cast('123' as int),Cast('200-08-08' ad datetime) from T_Person;
或者Convert(datetime,'2009-09-09') convert(varchar(50),1234)

select IsNull(FName,'佚名') as 姓名 from T_Person 如果為空白則返回佚名,否則返回FName

case的使用
select name,
(case level
when 1 then '普通使用者'
when 2 then '會員'
when 3 then 'VIP'
else '未知客戶'
此處無then!
end) as 客戶類型 from T_Person;
注意sql語句中的case的括弧為小括弧!

select name,
(case 若case不是固定值,則case後無欄位名
when salary<2000 then '低收入'
when salary>4000 then '高收入'
else '一般收入'

end) as 收入水平 from T_Person;

select *from (select u.User_Name,u.Name,l.Operation_Time,l.Content from user_info u, operation_log l where u.ID = l.User_ID)as aa where user_ID=1;

自動對查詢結果添加序號
"SET @row_number =0; select @row_number := @row_number+1 AS 序號,data_name as 日期 from dicdata_type_info where id>5;

對於設有外鍵的值進行操作時需先取消其對外鍵的檢查
set FOREIGN_KEY_CHECKS=0;
insert into dictionary_info (pid,data_name,data_type_id,del_flg,lastupdateuser,lastupdatetime)values(0,'" + data_name + "',200,0,1,'20120202');
set FOREIGN_KEY_CHECKS=1; 

-----------------------------------------------------------------------

建立日誌的函數
public void CreateLog(string log)
        {
            string time = DateTime.Now.ToString("yyyyMMddhhmmss");
            StreamWriter sw = new StreamWriter("Log.txt",true,System.Text.Encoding.GetEncoding("UTF-8"));
            sw.WriteLine(time+":"+ log);
            sw.Flush();
            sw.Close();
        }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.