C#技巧記錄——持續更新

做爲一名非主修C#的程序員,在此記錄下學習與工做中C#的有用內容,持續更新程序員

對類型進行約束,class指定了類型必須是引用類型,new()指定了類型必須具備一個無參的構造函數,規定T類型必須實現IUser,規定T必須爲struct算法

where T : class, new(), T:IUser, T:Struct

 

建立別名,實現C的typedef相似的功能sql

using MyInt=System.Int32;//爲Int32定義別名

 建立從當日00:00:00開始的時間json

DateTime date=DateTime.Now;
date=date.Date;    //經過返回時間的日期部分來解決時間置爲0的問題

 

 建立從當月1日到最後一天的時間swift

DateTime start = DateTime.Now.AddDays(-(int)DateTime.Now.Day + 1).Date;
DateTime end = start.AddMonths(1).AddDays(-1);

 獲取從當年第一天到最後一天的時間數組

DateTime start = DateTime.Now.AddDays(-DateTime.Now.DayOfYear+1).Date;
DateTime end = start.AddYears(1);

 獲取當季度第一天到最後一天app

int quarter = 0;
                switch (DateTime.Now.Month)
                {
                    case 3:
                    case 4:
                    case 5:
                        quarter = 3;break;
                    case 6:
                    case 7:
                    case 8:
                        quarter = 6; break;
                    case 9:
                    case 10:
                    case 11:
                        quarter = 9; break;
                    case 12:
                    case 1:
                    case 2:
                        quarter = 12; break;
                }
                DateTime start = DateTime.Now.AddDays(-DateTime.Now.DayOfYear+1).Date.AddMonths(quarter-1);
                DateTime end = start.AddMonths(3).AddDays(-1);

 定義長字符串包含特殊字符dom

string longStr = @"\[][;\&";

條件編譯ide

//DEBUG通常爲編譯器預約義的特殊變量,用於表示是否爲調試模式
//也能夠自定義,使用#define,並聲明在文件開始處,同C/C++
#if DEBUG
            Console.Write("debug");
#else
            Console.Write("un debug");
#endif
          
#if aa
            Console.WriteLine("我是A");
#else
            Console.WriteLine("我是B");
#endif

 ref out函數

//經過ref傳遞引用
//使用ref傳遞的值必須初始化
void show(ref int x)
{
    Console.Write(x)
}
int i=9;
show(ref i);

//解決了ref須要初始化的問題,使用out不須要對變量進行初始化
void show(out int x)
{
    Console.Write(x)
}
int i;
show(out i);

 命名參數

//能夠隨意交換實參的順序,冒號以前指定參數名,冒號以後指定值,與swift一致
public static void show(int x,int y)
{
        Console.Write("{0},{1}",x,y);
}
show(y:9,x:20);

 自動實現屬性

public int Age
{
        get;set;
}

 靜態構造函數

//在第一次引用類型的以前調用靜態構造函數
class test
    {
        static int count;
        static test()
        {
            count = 1;
        }
        public test()
        {
            
        }
        public  void show()
        {
            Console.Write(count);
        }
    }

 readonly

 class test
    {
        readonly int count=0;//只容許在初始化或構造函數中修改值
        public test()    
        {
            count = 1;
            
        }
        public  void show()
        {
            //count = 3;    錯誤
            Console.Write(count);
        }
        public int Age
            {
                get;set;
            }
    }

 匿名類型

//常使用建立類的方式來描述json對象,並須要每次建立新的類,
//使用匿名對象即可解決此問題
 var a = new { age = 0,name="lilei" };
 Console.Write(a.age+" "+a.name);

 

合併運算符

//當咱們在使用可空類型的時候常常須要判斷值是否爲空
//例如
int ? x;
if(x==null)
{
 //...   
}
else
{
    //...
}
//這個時候咱們即可以使用合併運算符來處理
// 當x非空時,a的值爲x的值。若x爲空,a的值爲0;
int a=x??0;

 

多維數組定義

//數組定義自己並不困難,這裏僅做爲和C不一樣的風格才記錄下來,以提醒本身
int [,] users=new int[2,2];

 排序

//數組提供的快速排序算法
//要求數組類型是已實現了IComparable接口的類型
int[] te = { 555,6,2,1,65,99,45,63};
            
Console.Write("*******************\n");
Array.Sort(te);
for (int i = 0; i < te.Length; i++)
{
    Console.Write(te[i] + "\n");
}

 

 字符串分割匹配多個字符

str.Split('a','b','c');

  使用\r\n分割字符串

var infoStr = examInfo.Split(new string[] { "\r\n" },
                        StringSplitOptions.RemoveEmptyEntries);

 linq

//linq語法與sql相似,不一樣之處須要將from提早,
//便於類型推測,select語句放到最後
//其中d爲查詢後的對象
//in後爲查詢的數據來源
int[] ary = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            var resul = from d in ary
                        where d == 1
                        select d;
            foreach (var item in resul)
            {
                MessageBox.Show(item.ToString());
            }

//可爲查詢對象設置類型,from後的int,以下
//若是類型錯誤會產生運行時異常
int[] ary = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            var resul = from int d in ary
                        where d == 1
                        select d;
            foreach (var item in resul)
            {
                MessageBox.Show(item.ToString());
            }

 使用共享模式讀寫文件

//共享模式寫文件
using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
            {
                fs.SetLength(0);
                using (StreamWriter writer = new StreamWriter(fs,Encoding.Default))
                {
                    string infos = JsonConvert.SerializeObject(info.data);
                    writer.Write(infos);
                    writer.Flush();
                    writer.Dispose();
                }
                fs.Dispose();
            }
//共享模式讀取文件
            using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite,FileShare.ReadWrite))
            {
                fs.SetLength(0);
                using (StreamReader reader = new StreamReader(fs))
                {
                    string lifeStr=reader.ReadToEnd();
                }
                fs.Dispose();
            }

static&&const

static 表示靜態的
const 表示靜態的常量

using static

using static Console;

class Pragram
{
    //使用using static已經導入了,這裏不用加Console
     Write("Hello");   
}

 ILDSAM

C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.1 Tools
//在相似目錄下

 byte、sbyte

byte:無符號
sbyte:有符號

 插值字符串

int a=9;
string b=$"a:{a}";//使用變量或表達式值填充

 lambda表達式

int getDouble(int x)=>x*x;

 可變個數的參數

//使用關鍵字params
public static void G(params int[] d)
        {
            foreach (var item in d)
            {
                Write(item);
            }
        }

 構造函數初始化器

class A
{
        A(int i)
        {
            B = i;
        }
//自動調用相應的構造函數,在此構造函數體以前執行
        A():this(1)
        {
            
}

靜態構造函數

static A()
{
      //在第一次調用以前自動初始化          
}

readonly

class A
{
    readonly int a;
    A()
    {
        //只能在構造函數中初始化,不然將爲該類型的默認值
        a=9;
    }    
}

 表達式體屬性(聲明類成員時使用lambda)

class A
{
    int a;
    int b;
    int c=>a+b;
}

 匿名類型

var zhangsan=new 
{
     name="zhangsan";
     age=20   
};

 override new

若是你用override,則不管調用的是A類仍是B類中的TEST(),系統都會找到它實質類的TEST();
若是是用的New,則能夠經過類型轉換調用到基類的TEST();

 獲取[Description("")]

public static class EnumHelper
    {
        public static string GetDescription(this Enum enumeration)
        {
            Type type = enumeration.GetType();
            MemberInfo[] memInfo = type.GetMember(enumeration.ToString());
            if (null != memInfo && memInfo.Length > 0)
            {
                object[] attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
                if (null != attrs && attrs.Length > 0)
                    return ((DescriptionAttribute)attrs[0]).Description;
            }
            return enumeration.ToString();
        }
    }

 is as

is返回判斷結果true false
as返回轉換後的引用,若是轉換失敗返回null,
轉換失敗均不拋出異常

 空值運算符

//空指針異常
//string i=null ;
//Console.WriteLine(i.ToString());

//輸出空白字符
string i = null;
Console.WriteLine(i?.ToString());
Console.WriteLine("end");

 nameof

//獲取方法或類的名稱

 default獲取類型默認值

int i=default(int);

 checked unchecked

檢測代碼塊是否計算過程當中發生溢出,通常不須要unchecked(默認爲不檢測)

 

 

 ?空值傳播與??空值合併

? //若是引用爲空,則直接返回null
?? //若是不爲空則返回變量值,不然返回??以後的值
var
x = new { a = "a", b = "b" }; //若是x爲空,則直接返回null var xx = x?.a ?? "";

 action func

void a() { }
int b() { return 0; }
void test()
{
    Action ax=new Action(a);
    Func<int> af = new Func<int>(b);
}

 Lazy<>延遲加載

   public class Student
   {
      public Student()
      {
         this.Name = "DefaultName";
         this.Age = 0;
         Console.WriteLine("Student is init...");
      }

      public string Name { get; set; }
      public int Age { get; set; }
   }

 Lazy<Student> stu = new Lazy<Student>();
         if(!stu.IsValueCreated)
            Console.WriteLine("isn't init!");
         Console.WriteLine(stu.Value.Name);
         stu.Value.Name = "Tom";
         stu.Value.Age = 21;
         Console.WriteLine(stu.Value.Name);
         Console.Read();

 WeakReference弱引用對象

弱引用:在引用對象的同時,容許垃圾回收該對象。
對於那些建立便宜但耗費大量內存的對象,即但願保持該對象,又要在應用程序須要時使用,
同時但願GC必要時回收時,能夠考慮使用弱引用

獲取隨機文件名

System.Console.WriteLine(Path.GetRandomFileName());
System.Console.WriteLine(Path.GetTempFileName());
System.Console.WriteLine(Path.GetTempPath());

 顯示TODO標

視圖->任務列表

 類型轉換

Convert.ChangeType(value, property.PropertyType);

 

相關文章
相關標籤/搜索