C#基础
c#笔记 by Forget December
Keyword
params
as ,is
using System.Data;
using System;
namespace vscode
{
public class SqlCon
{
static void Main()
{
Person person=new Person();
Employee employee=new Employee();
if(employee is Person)//employee是否能不强制转化成Person类型
{
Console.WriteLine("check1");
}
Person p= employee as Person;//将employee转化成Person类型,转化失败p=null
if(p!=null)
{
Console.WriteLine("check2");
}
Console.WriteLine("please anykey to exit...");
Console.ReadKey();
}
}
}
-----------------------------------------------------------------------------------------------------
| 输出:check1 |
| check2 | -----------------------------------------------------------------------------------------------------
using System.Data;
using System;
namespace vscode
{
public class SqlCon
{
static void Main()
{
Person person=new Person();
Employee employee=new Employee();
if(person is Employee)
{
Console.WriteLine("check1");
}
Employee e=person as Employee;
if(e!=null)
{
Console.WriteLine("check2");
}
Console.WriteLine("please anykey to exit...");
Console.ReadKey();
}
}
}
-----------------------------------------------------------------------------------------------------
输出:
ref
static void Method(ref int num)
{
num+=50;
}
static void Main()
{
int num=1;
Method(ref num);
Console.WriteLine(num);
Console.WriteLine("press any key to continue...");
Console.ReadKey();
}
-----------------------------------------------------------------------------------------------------
输出:51
static void Method( int num)
{
num+=50;
}
static void Main()
{
int num=1;
Method( num);
Console.WriteLine(num);
Console.WriteLine("press any key to continue...");
Console.ReadKey();
}
-----------------------------------------------------------------------------------------------------
输出:1
out
The only difference with ref
is that a parameter you pass as the out
parameter doesn’t need to be initianized while the ref
parameter need to be set to something before you use it.
public static void OutDouble(out int outInt)
{
outInt = 2;
Console.WriteLine("outInt is:"+outInt);
}
public static void RefDouble(ref int parInt)
{
parInt *= 2;
Console.WriteLine("refInt is:"+parInt);
}
public static void NormalDouble(int IntPar)
{
IntPar+=10;
Console.WriteLine("normalInt is:" + IntPar);
}
static void Main(string[] args)
{
int refInt;
int outInt;
int normalInt;
OutDouble(out outInt);
RefDouble(ref refInt);//<font color='red'>error: use the uninitianized variable</font>
NormalDouble(normalInt);//<font color='red'>error: use the uninitianized variable</font>
Console.ReadKey();
}
delegate
Class: declare the type => declare the type’s variable => fill the variable => use the variable
Delegate: declare the delegate(class) => declare the variable in the type of delegate =>create the delegate instance and assign its reference to the variable ,then add the first method
=> user delegate object
public class SqlCon
{
void PrintHigh(int value)
{
Console.WriteLine("{0}--high",value);
}
void PrintLow(int value)
{
Console.WriteLine("{0}--low",value);
}
delegate void Mydele(int a);
static void Main(string[] args)
{
SqlCon con=new SqlCon();
Random random=new Random();
int randValue=random.Next(1,10);//1~9
Mydele dele=randValue>5?new Mydele(con.PrintHigh):new Mydele(con.PrintLow);
dele(randValue);
Console.ReadKey();
}
}
the combination of delegate
if the return type is not void ,only the last method will be returned.
all the methods in the combination uses the same paremeters
static int PrintHigh(int value)
{
Console.WriteLine("{0}--high",value);
return 99;
}
static int PrintLow(int value)
{
Console.WriteLine("{0}--low",value);
return 10;
}
delegate int Dele(int a);
static void Main(string[] args)
{
Dele deleC;
Dele deleA=new Dele(PrintHigh);
Dele deleB=new Dele(PrintLow);
deleC=SqlCon.PrintHigh;
deleC+=SqlCon.PrintLow;
deleC+=SqlCon.PrintHigh;
deleC+=SqlCon.PrintLow;
Console.WriteLine(deleC(55));//they use the same parameter of '55'
Console.ReadKey();
}
-----------------------------------------------------------------------------------------------------
输出:55--high
55--low
55--high
55--low
10
when the return type is void,all the method in the list will be called
static void PrintHigh(int value)
{
Console.WriteLine("{0}--high",value);
}
static void PrintLow(int value)
{
Console.WriteLine("{0}--low",value);
}
delegate void Dele(int a);
static void Main(string[] args)
{
Dele deleC;
Dele deleA=new Dele(PrintHigh);
Dele deleB=new Dele(PrintLow);
deleC=SqlCon.PrintHigh;
deleC+=SqlCon.PrintLow;
deleC(55);
Console.ReadKey();
}
-----------------------------------------------------------------------------------------------------
输出: 55--high
55--low
Innominate method
delegate int Dele(int a);
static void Main(string[] args)
{
Dele dele=new Dele(delegate(int a)
{
return a*11;
});
Console.WriteLine(dele(9));
Console.ReadKey();
}
the params keyword will be ommited when use delegate
delegate void Mydele(params object[] items);
static void Main(string[] args)
{
//ShowItems('a',55,"good morning");
Mydele dele=delegate(object[] items)
{
for(int i=0;i<items.Length;i++)
{
Console.WriteLine(items[i]);
}
};
dele("string",5,'x');
Console.ReadKey();
}
use innominate method to capture the variable,then you can see the variable in the inner statement
delegate void MydeleA();
static void Main(string[] args)
{
MydeleA deleA;
{
int x=5;
deleA=delegate()
{
Console.WriteLine("the value of x is "+x);
};
}
deleA();
Console.ReadKey();
}
Lambda
Mydele mydeleA=delegate(int x){Console.WriteLine("hello");return 2*x;};
Mydele mydeleB=(int x)=>{Console.WriteLine("hello");return 2*x;};
Mydele mydeleC=(x)=>{Console.WriteLine("hello");return 2*x;};
Mydele mydeleD=x=>{Console.WriteLine("hello");return 2*x;};
Mydele mydeleE=x=>2*x;
var,dynamic
var | dynamic | |
---|---|---|
make effort | while compiling | runtime |
initnize before using? | true | false |
var a=11;//compile successfully
var a;//compile fail
dynamic b=44;//compile successfully
dynamic b;//compile successfully
可空类型(int? id,id??636)
public IActionResult Details(int? id)
{
Student model = IResposity.GetStudent(id??636);
ViewData["Title"] = "Details";
return View(model);
}
Transform
1.C#中类的转换(显性,隐性)
-
仅发生在父类和子类之间
-
由高级转化为低级不需要强制转换,由低级转化为高级需要强制转换(显式转换):例如
class Person
{
public string name;
public int age ;
}
class Employee:Person
{
int id;
string type;
}
Employee employee = new Employee();
Person person = new Person();
person=employee;
employee=(Person)person;
object-oriented
1.子类不继承父类中初始化的值
class Person
{
public string name="Tim";
public int age =19;
}
class Employee:Person
{
int id;
string type;
}
Employee employee = new Employee();
Person person = new Person();
Console.WriteLine(employee.name + " " + employee.age);
-----------------------------------------------------------------------------------------------------
输出结果:0而不是:Tim 19
database
1.examples of sql server(2014) connection
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
namespace SqlServerCon
{
class Program
{
static void Main(string[] args)
{
string connString = @"DATA Source=WIN10-802131710;Database=mydb;User ID=sa;Pwd=root;";
SqlConnection connection = new SqlConnection(connString);
string sql = "select * from student";
SqlCommand command = new SqlCommand(sql, connection);
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter(command);
sda.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
string name = dr["name"].ToString();
int id = Convert.ToInt32(dr["id"]);
Console.WriteLine(name + " " + id);
}
connection.Close();
sda.Dispose();
Console.WriteLine("press any key to exit...");
Console.ReadKey();
}
}
}
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
namespace SqlServerCon
{
class Program
{
static void Main(string[] args)
{
string connString = @"DATA Source=WIN10-802131710;Database=mydb;User ID=sa;Pwd=root;";
SqlConnection connection = new SqlConnection(connString);
string sql = "select * from student";
SqlCommand command = new SqlCommand(sql,connection);
if(connection.State==ConnectionState.Closed)
{
connection.Open();
}
SqlDataReader dataReader = command.ExecuteReader();
while(dataReader.Read())
{
string name = dataReader["name"].ToString();
string id = dataReader["id"].ToString();
Console.WriteLine(name+" "+id);
}
}
}
}
thread
async/await
Method Task<int> t1
returns a int type that doesn’t has any value and is just as a placeholder,then the method Task<int> t2
will start.
If t1.Result
or t2.Result
doesn’t have any value in Console.WriteLine
,the process will be block and wait until task t1 and t2 are finished.
using System;
using System.Diagnostics;
using System.Net;
using System.Threading.Tasks;
class MyDownloadString
{
Stopwatch sw = new Stopwatch();
public void DoRun()
{
const int LargeNumber = 6000000;
sw.Start();
Task<int> t1 = CountCharactersAsync( 1, "http://www.microsoft.com" );
Task<int> t2 = CountCharactersAsync( 2, "http://www.illustratedcsharp.com" );
CountToALargeNumber( 1, LargeNumber );
CountToALargeNumber( 2, LargeNumber );
CountToALargeNumber( 3, LargeNumber );
CountToALargeNumber( 4, LargeNumber );
Console.WriteLine( "Chars in http://www.microsoft.com : {0}", t1.Result );
Console.WriteLine( "Chars in http://www.illustratedcsharp.com: {0}", t2.Result );
}
private async Task<int> CountCharactersAsync( int id, string site )
{
WebClient wc = new WebClient();
Console.WriteLine( "Starting call {0} : {1, 4:N0} ms",id, sw.Elapsed.TotalMilliseconds );
string result = await wc.DownloadStringTaskAsync( new Uri( site ) );
Console.WriteLine( " Call {0} completed : {1, 4:N0} ms",id, sw.Elapsed.TotalMilliseconds );
return result.Length;
}
private void CountToALargeNumber( int id, int value )
{
for ( long i=0; i < value; i++ );
Console.WriteLine( " End counting {0} : {1, 4:N0} ms",id, sw.Elapsed.TotalMilliseconds );
}
}
class SqlCon
{
static void Main()
{
MyDownloadString ds = new MyDownloadString();
ds.DoRun();
Console.ReadKey();
}
}
-----------------------------------------------------------------------------------------------------
输出:
Starting call 1 : 39 ms
Starting call 2 : 333 ms
End counting 1 : 358 ms
End counting 2 : 372 ms
End counting