作为一名非主修C#的程序员,在此记录下学习与工作中C#的有用内容,持续更新

对类型进行约束,class指定了类型必须是引用类型,new()指定了类型必须具有一个无参的构造函数,规定T类型必须实现IUser,规定T必须为struct

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

创建别名,实现C的typedef类似的功能

using MyInt=System.Int32;//为Int32定义别名

 创建从当日00:00:00开始的时间

DateTime date=DateTime.Now;
date=date.Date; //通过返回时间的日期部分来解决时间置为0的问题

 创建从当月1日到最后一天的时间

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

 获取从当年第一天到最后一天的时间

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

 获取当季度第一天到最后一天

int quarter = ;
switch (DateTime.Now.Month)
{
case :
case :
case :
quarter = ;break;
case :
case :
case :
quarter = ; break;
case :
case :
case :
quarter = ; break;
case :
case :
case :
quarter = ; break;
}
DateTime start = DateTime.Now.AddDays(-DateTime.Now.DayOfYear+).Date.AddMonths(quarter-);
DateTime end = start.AddMonths(3).AddDays(-1);

 定义长字符串包含特殊字符

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

条件编译

//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=;
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:,x:);

 自动实现属性

public int Age
{
get;set;
}

 静态构造函数

//在第一次引用类型的之前调用静态构造函数
class test
{
static int count;
static test()
{
count = ;
}
public test()
{ }
public void show()
{
Console.Write(count);
}
}

 readonly

 class test
{
readonly int count=;//只允许在初始化或构造函数中修改值
public test()
{
count = ; }
public void show()
{
//count = 3; 错误
Console.Write(count);
}
public int Age
{
get;set;
}
}

匿名类型

//常使用创建类的方式来描述json对象,并需要每次创建新的类,
//使用匿名对象便可解决此问题
var a = new { age = ,name="lilei" };
Console.Write(a.age+" "+a.name);

合并运算符

//当我们在使用可空类型的时候经常需要判断值是否为空
//例如
int ? x;
if(x==null)
{
//...
}
else
{
//...
}
//这个时候我们便可以使用合并运算符来处理
// 当x非空时,a的值为x的值。若x为空,a的值为0;
int a=x??;

多维数组定义

//数组定义本身并不困难,这里仅作为和C不同的风格才记录下来,以提醒自己
int [,] users=new int[,];

 排序

//数组提供的快速排序算法
//要求数组类型是已实现了IComparable接口的类型
int[] te = { ,,,,,,,}; Console.Write("*******************\n");
Array.Sort(te);
for (int i = ; 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 = { , , , , , , , , };
var resul = from d in ary
where d ==
select d;
foreach (var item in resul)
{
MessageBox.Show(item.ToString());
} //可为查询对象设置类型,from后的int,如下
//如果类型错误会产生运行时异常
int[] ary = { , , , , , , , , };
var resul = from int d in ary
where d ==
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();
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();
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. Tools
//在类似目录下

 byte、sbyte

byte:无符号
sbyte:有符号

插值字符串

int a=;
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()
{ }

静态构造函数

static A()
{
//在第一次调用之前自动初始化
}

readonly

class A
{
readonly int a;
A()
{
//只能在构造函数中初始化,否则将为该类型的默认值
a=;
}
}

 表达式体属性(声明类成员时使用lambda)

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

匿名类型

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

 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 > )
{
object[] attrs = memInfo[].GetCustomAttributes(typeof(DescriptionAttribute), false);
if (null != attrs && attrs.Length > )
return ((DescriptionAttribute)attrs[]).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 ; }
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 = ;
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 = ;
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);

 base64转图片

public static void SaveImage(string logoBase64, string path, string imageName)
{
string finalPath = Path.Combine(path, imageName);
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
File.WriteAllBytes(finalPath, Convert.FromBase64String(logoBase64));//将base64转成图片
}

 使用保留的关键字作为变量名

//在变量名称前添加@
//为跨平台提供了便利
public class Test{
public string @class{get;set;}
}
 
 
 

C#技巧记录——持续更新的更多相关文章

  1. python3.4学习笔记(六) 常用快捷键使用技巧,持续更新

    python3.4学习笔记(六) 常用快捷键使用技巧,持续更新 安装IDLE后鼠标右键点击*.py 文件,可以看到Edit with IDLE 选择这个可以直接打开编辑器.IDLE默认不能显示行号,使 ...

  2. git使用技巧集合(持续更新中)

    git使用技巧集合(持续更新中) 在团队协作中,git.svn等工具是非常重要的,在此只记录一些git使用过程中遇到的问题以及解决方法,并且会持续更新. 1.git commit之后,还没push,如 ...

  3. tp5 使用技巧(持续更新中...)

    tp5 使用技巧(持续更新中...) 1.自动写入时间 create_time和update_time 使用save方法才行,insert方法不生效,不知为何 2.过滤字段 allowfield和st ...

  4. JavaScript 使用技巧(持续更新)

    JavaScript 使用技巧(持续更新) 类型检测 使用Object.prototype.toString.call(obj)的方式. 因为无论typeof还是instanceof都无法做到精确判断 ...

  5. 总结js常用函数和常用技巧(持续更新)

    学习和工作的过程中总结的干货,包括常用函数.常用js技巧.常用正则表达式.git笔记等.为刚接触前端的童鞋们提供一个简单的查询的途径,也以此来缅怀我的前端学习之路. PS:此文档,我会持续更新. Aj ...

  6. Word, PPT和Excel的常用技巧(持续更新)

    本文的目的是记录平时使用Word, PowerPoint和Excel的过程中的一些小技巧,用于提升工作效率. 此文会不定期的更新,更新频率完全取决于实际使用遇到的问题的次数. 目录 Word Powe ...

  7. SAM 做题笔记(各种技巧,持续更新,SA)

    SAM 感性瞎扯. 这里是 SAM 做题笔记. 本来是在一篇随笔里面,然后 Latex 太多加载不过来就分成了两篇. 标 * 的是推荐一做的题目. trick 是我总结的技巧. I. P3804 [模 ...

  8. DP刷题记录(持续更新)

    DP刷题记录 (本文例题目前大多数都选自算法竞赛进阶指南) TYVJ1071 求两个序列的最长公共上升子序列 设\(f_{i,j}\)表示a中的\(1-i\)与b中色\(1-j\)匹配时所能构成的以\ ...

  9. Redis基础知识之————使用技巧(持续更新中.....)

    一.key 设计技巧 把表名转换为key前缀 如, tag: 第2段放置用于区分区key的字段--对应mysql中的主键的列名,如userid 第3段放置主键值,如2,3,4...., a , b , ...

随机推荐

  1. 【TensorFlow篇】--反向传播

    一.前述 反向自动求导是 TensorFlow 实现的方案,首先,它执行图的前向阶段,从输入到输出,去计算节点值,然后是反向阶段,从输出到输入去计算所有的偏导. 二.具体 1.举例 图是第二个阶段,在 ...

  2. 【重学计算机】计组D3章:运算方法与运算器

    1. 定点数运算及溢出 定点数加减法:减法化加法,用补码直接相加,忽略进位 溢出:运算结果超出了某种数据类型的表示范围 溢出检测方法:统一思想概括为正正得负或负负得正则溢出,正负或负正不可能溢出 方法 ...

  3. chrome 错误 ERR_CACHE_READ_FAILURE

    问题现象 谷歌浏览器,点击后退按键提示:ERR_CACHE_READ_FAILURE 错误 解决办法 1. chrome://flags/#enable-simple-cache-backend 2. ...

  4. vue-router导航守卫(router.beforeEach())的使用

    好久没写一些东西了,总是感觉有啥缺少的.~~~~恰好碰到最近在写一个移动端项目,遇到了如何使同一个链接在不同条件下跳转到不同路由组件问题,譬如大家经常看到手机中没登录跳转登录页,登陆后跳转个人信息页等 ...

  5. Eureka服务下线后快速感知配置

    现在由于eureka服务越来越多,发现服务提供者在停掉很久之后,服务调用者很长时间并没有感知到变化,依旧还在持续调用下线的服务,导致长时间后才能返回错误,因此需要调整eureka服务和客户端的配置,以 ...

  6. Go 只读/只写channel

    Go中channel可以是只读.只写.同时可读写的. //定义只读的channel read_only := make (<-chan int) //定义只写的channel write_onl ...

  7. 深入解析ThreadLocal 详解、实现原理、使用场景方法以及内存泄漏防范 多线程中篇(十七)

    简介 从名称看,ThreadLocal 也就是thread和local的组合,也就是一个thread有一个local的变量副本 ThreadLocal提供了线程的本地副本,也就是说每个线程将会拥有一个 ...

  8. cocos creator主程入门教程(三)—— 资源管理

    五邑隐侠,本名关健昌,10年游戏生涯,现隐居五邑.本系列文章以TypeScript为介绍语言. 在初识篇,我介绍过怎样加载prefab.cocos提供了一系列的加载接口,包括cc.loader.loa ...

  9. [TCP/IP] 网络层-简单查看路由表

    使用抓包工具排除网络故障:1.如果一台计算机在网络上发广播包,广播的mac地址是全ff,就有可能堵塞2.使用抓包工具,检测广播包和多播包 网络畅通的条件:数据包有去有回1.路由器使用路由表找到目标网段 ...

  10. oracle学习笔记(二) 基本数据类型

    常用的数据类型 int number number(4,1) 999.1 四个数字,小数位一位 decimal date 日期 格式如下: 注意:日期类型的字段格式,可以通过以下三种方式: 1. da ...