C#基础

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

C#基础

ForgetDecember   2019-12-21 我要评论

 

 

 

 

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

 vardynamic
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 3           :  390 ms
End counting 4           :  406 ms
Call 1 completed         : 1,208 ms
Chars in http://www.microsoft.com       : 166458

除一般方法,Lambda表达式和匿名方法也可作为异步的对象。

class SqlCon
{
  public Task<double> CountAsync(double num1,double num2)
  {
     return Task.Run(() =>
{
for (int i = 0; i < 1000000; i++)
{
num1 = num1 / num2;
}
return num1;
});
  }
  public async void DisplayValue()
  {
     double result=await CountAsync(99999.0,100.0);
     Console.WriteLine("the result = {0}",result);
  }
  static void Main()
  {
      SqlCon con=new SqlCon();
      con.DisplayValue();
      Console.WriteLine("Hello");
      Console.ReadKey();      
  }
}

异步方法的三种返回类型

1.返回Task<T>

using System;
using System.Threading.Tasks;

namespace vscode
{
  class SqlCon
  {
     static void Main()
    {
        Task<int> t=DoAsyncStuff.CalucatedSumAsync(5,6);
        Console.WriteLine("value= {0}",t.Result);
        Console.ReadKey();    
    }
  }
  static class DoAsyncStuff
  {
     public static async Task<int> CalucatedSumAsync(int a,int b)
    {
        int sum=await Task.Run(()=>GetSum(a,b));
        return sum;
    }
     public static int GetSum(int a,int b)
    {
        return a+b;
    }
  }
}

2.返回Task

using System;
using System.Threading.Tasks;

namespace vscode
{
  class SqlCon
  {
     static void Main()
    {
        Task task=DoAsyncStuff.CalucatedSumAsync(5,6);
        task.Wait();
        Console.WriteLine("press any key to contiune...");
        Console.ReadKey();    
    }
  }
  static class DoAsyncStuff
  {
     public static async Task CalucatedSumAsync(int a,int b)
    {
        int sum=await Task.Run(()=>GetSum(a,b));
        Console.WriteLine("value= {0}",sum);
    }
     public static int GetSum(int a,int b)
    {
        return a+b;
    }
  }
}

3.“调用并忘记”

using System;
using System.Threading.Tasks;

namespace vscode
{
  class SqlCon
  {
     static void Main()
    {
        DoAsyncStuff.CalucatedSumAsync(5,6);
        System.Threading.Thread.Sleep(200);
        Console.WriteLine("press any key to contiune...");
        Console.ReadKey();    
    }
  }
  static class DoAsyncStuff
  {
     public static async void CalucatedSumAsync(int a,int b)
    {
        int sum=await Task.Run(()=>GetSum(a,b));
        Console.WriteLine("value= {0}",sum);
    }
     public static int GetSum(int a,int b)
    {
        return a+b;
    }
  }
}

异步方法的控制流

using System;
using System.Threading.Tasks;

namespace vscode
{
  class SqlCon
  {
     static void Main()
    {
        DoAsyncStuff.CalucatedSumAsync(5,6);
        System.Threading.Thread.Sleep(200);
        Console.WriteLine("press any key to contiune...");
        Console.ReadKey();    
    }
  }
  static class DoAsyncStuff
  {
     public static async void CalucatedSumAsync(int a,int b)
    {
        Console.WriteLine("misson started!");
        await Task.Run(()=>{
           for(int i=0;i<100000000;i++)
          {
              a=a*b;
          }
           Console.WriteLine("value = {0}",a);
        });
        Console.WriteLine("misson completed!");
    }
  }
}


-----------------------------------------------------------------------------------------------------
输出:
misson started!
press any key to contiune...
value = 0
misson completed!

使用Wait()使主线程等待异步线程执行完.

class MyClass
{
  public int Get10() // Func<int> compatible
  {
     return 10;
  }
  public async Task DoWorkAsync()
  {
     Func<int> ten=new Func<int>(Get10);
     int a=await Task.Run(ten);
     int b=await Task.Run(new Func<int>(Get10));
     int c=await Task.Run(()=>10);
     Console.WriteLine( "{0} {1} {2}", a, b, c );
  }
}

class Program
{
  static void Main()
  {
     Task task=(new MyClass()).DoWorkAsync();
     task.Wait();
     Console.WriteLine("press any key to continue...");
     Console.ReadKey();
  }
}
-----------------------------------------------------------------------------------------------------
输出:
10 10 10
press any key to continue...
-----------------------------------------------------------------------------------------------------
若没有wait()输出:
press any key to continue...
10 10 10

Task.Run()四种委托类型参数

using System;
using System.Threading.Tasks;

static class MyClass
{
  public static async Task DoWorkAsync()
  {
      //这里研究的是最外层的Task.Run()
     await Task.Run(()=>Console.WriteLine(5));//Action(无参数,无返回类型的委托)
     Console.WriteLine(await Task.Run(()=>6));//Func<int>(返回int类型的委托)
     await Task.Run(()=>Task.Run(()=>Console.WriteLine(7))); //Func<Task>(返回Task的委托)
     int value=await Task.Run(()=>Task.Run(()=>8)); //Func<Task<int>>(返回Task<int>的委托)
     Console.WriteLine(value);
  }
}

class Program
{
  static void Main()
  {
     Task t = MyClass.DoWorkAsync();
     t.Wait();
     Console.WriteLine( "Press Enter key to exit" );
     Console.Read();
  }
}

可访问性

所有用户自定义类型(接口,类和结构体)被调用时,要保证该类型可访问性不小于调用它的函数

1573997090684

当Student类去掉public时

1573997144755

当IStudent接口去掉public时

1573997316399

Extension Method

using System;
namespace Interface
{
   public interface IClassA
  {
       public void Method1();
  }
}
namespace Extension
{
   using Interface;
   public static class ExtensionClassA
  {
       public static void Method2(this IClassA ca)
      {
           Console.WriteLine("ExtensionClassA.Method2()");
      }
  }
}
namespace vscode2
{
   using Interface;
   using Extension;
   public class ClassA:IClassA
  {
       public void Method1()
      {
           Console.WriteLine("ClassA.Method1()");
      }
  }
   public class Program
  {
       static void Main(string[] args)
      {
           ClassA a=new ClassA();
           a.Method1();
           a.Method2();
           return;
      }
  }
}
/*------------------------------------------------------------------
ClassA.Method1()
ExtensionClassA.Method2()
------------------------------------------------------------------*/

 

interface

通过接口调用方法

IStudentResposity IResposity=new MockStudentResposity();//IStudentResposity是接口 MockStudentResposity是实现接口的类

常用概念

函数签名

简单地说,签名由方法名称、它的参数类型和参数的修饰符组成。方法的签名不包括返回类型,并且不包括参数的名称。例:

void F();//签名是F()
int F(int x);//签名是F(int)
int F(out int x);//签名是F(out int),此处out指的是参数的修饰符

重载方法

函数名相同,但函数签名不同

/*1*/
int f(int n);
void f(int m);
//不是重载方法,签名相同
/*2*/
int f(int n);
int f(int n,int m);
//是

 

实例

文件操作实例

将一个文本文件中的空格,/r ...删掉

using System;
using System.IO;
using System.Text;

namespace vscode1
{
   class Program
  {
       static void Main(string[] args)
      {
           string path1="D:\\timdownload\\suijixulie.txt";
           string path2="D:\\timdownload\\Quantum.txt";
           // StreamReader sr=new StreamReader(path1);
           
           // for(int i=0;i<10;i++)
           // {
           //     char[] buff=new char[10000];
           //     sr.Read(buff,0,buff.Length);
           //     Console.WriteLine(buff);
           // }
           FileStream fs;
           FileStream fTarget;
           try
          {
               fs=new FileStream(path1,FileMode.Open,FileAccess.Read);
               fTarget=new FileStream(path2,FileMode.Open,FileAccess.Write);
          }
           catch
          {
               throw new FileNotFoundException();
          }
           
           byte[] buff=new byte[1000];
           char[] eplsion=new char[1000];
           long leftLength=fs.Length;
           int maxLength=buff.Length;
           int num;
           int fileStart=0;
           while(leftLength>0)
          {
               fs.Position=fileStart;
               if(leftLength>maxLength)
              {
                   num=fs.Read(buff,0,maxLength);
              }
               else
              {
                   num=fs.Read(buff,0,Convert.ToInt32(leftLength));
                   
              }
               string temp=Encoding.Default.GetString(buff);
               eplsion=temp.ToCharArray();
               for(int i=0;i<(leftLength>maxLength?maxLength:leftLength);i++)
              {
                   if(eplsion[i]=='1'||eplsion[i]=='0')
                  {
                       fTarget.WriteByte(buff[i]);
                  }
              }
               //Console.WriteLine(eplsion);  
               //Console.WriteLine(Encoding.Default.GetString(buff));
               leftLength-=maxLength;
               fileStart+=maxLength;
          }
           Console.WriteLine("press any key to continue...");
           
      }
  }
}

 

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们