结构体
结构体与类基本一致,但是不同的地方在于,结构体在栈上开辟空间,而类在堆上开辟空间.所以结构体是值类型而类是引用类型。还有就是结构体里不允许写无参构造必须写有参构造,但是可以写无参静态构造。结构体中不允许写析构代码。结构体只有一个父类object,不能被其他结构体或类继承,也不能继承自其他结构体或类。
语法如下:
静态类
静态类不能创建实实例对象,不能声明实例成员(实例变量,实例方法),只能声明静态方法,静态变量,静态构造方法,静态类只能有一个父类object。静态类一般用于设计工具类。
Sealed修饰符
sealed修饰的类不能被继承。sealed修饰的方法不能被重修(但至少被重写一次),
算数运算符重载
程序语言可以使用 关键字operator 根据需要对算数运算符进行重载,实现其他的功能。关系运算符全部可以重载,但是要成对重载。比如重载了> 必须重载 < ,重载了>= 必须重载 <= 等 。逻辑运算符中 && || 不能重载。 位运算符 ~可以被重载
注意:方法必须声明被 static,public 修饰,并且只能重载一元运算符(操作一个数字的运算符 与(&) 或(|) 非(!) 负号- 正号 + )
抽象类
用关键字修饰 abstract 的类,不能实例化对象。用关键字修饰 abstract 的方法没有方法体,C#与JAVA中的抽象方法完全一致。只不过C#重写父类方法是使用override修饰,而JAVA中不需要,最多可以选择加@override 注解。
接口
C#中的接口除了在实现接口的时候用 冒号 实现 以外,其他的大部分特性与JAVA完全一致。并且既有继承又有实现接口的时候,父类在第一位,其次在后面。
向上转型
C#与java 的接口不一样的地方有:C#接口中可以声明属性并写属性访问器,而JAVA中不行.C#中的继承可以是多继承,而JAVA中就不行。
命名空间
1,C#中的命名空间相当于JAVA中的Pakage,里面的成员只能存放类,方法,结构体,接口等类型
2,命名空间可以嵌套使用,并且命名空间如果和类的名字相同时应该 namespace.class 这种格式引用类。
3,使用 using xxxx; 来引用命名空间,如果多个命名空间名字一样,则说明他们是一个命名空间的
委托
C# 里面有一种方法类型叫做委托
实例化 一个委托对象 需要用一个方法来实例化
这个方法的返回值类型和参数列表也保持一致
第二种写法
在这里testDelegate 指向了一个方法,可以直接使用。
组合委托(多播委托),可以使用运算符 + 来组合两个委托
这样就简洁了代码
也可以使用 - 号来解除委托
匿名方法委托写法如下:
C#的 lamda表达式写法如下:
一种熟悉的感觉,因为JAVA的lamda表达式也是这样写的,如果多写lamda表达式可以使更多程序员看懂。并且也能提高程序的运行效率
委托回调
当有一个需求是当下载器下载完成后通知用户下载完成,首先知道下载任务进度的是下载器自己,然后就是要通过记录用户,下载完成后就通知该用户。这一系列操作用到了设计模式--委托。代码如下:
以上代码存在扩展性问题,因此用delegate 优化
using System;
using System.Threading;
using UserNamespace;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UserNamespace.Studnet;
namespace ConsoleApp1{
class DownloadTool
{
public DownloadComplete downloadComplete;
//下载数据
public void DownloadData(string url,string username)
{
//模拟数据下载
for (int i = 0; i <= 100; i += 5)
{
//线程休眠:让程序休眠50毫秒
Thread.Sleep(10);
//清屏
Console.Clear();
Console.WriteLine($"数据下载中......({i})");
}
Console.WriteLine("恭喜 " + username + " 您的数据下载完成!");
downloadComplete("hello world!");
}
}
class Person {
string username;
public string Username{
get{ return this.username;}
}
public Person(string username) {
this.username = username;
Console.WriteLine(username);
}
public void DownloadData(String url) {
DownloadTool downloadTool = new DownloadTool();
downloadTool.downloadComplete = DealWithDownloadData;
downloadTool.DownloadData(url,"小张");
}
public void DealWithDownloadData(String result)
{
ConsoleColor originalColor = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(result);
Console.ForegroundColor = originalColor;
}
}
delegate void DownloadComplete(string result);
class Program
{
//下载工具类(模拟迅雷等下载工具)
static void Main(string[] args)
{
Person person = new Person("小明");
person.DownloadData("www.baidu.com");
}
订阅/发布(观察者)模式
思想:将一组操作封装起来,不关心订阅者是谁,只要实现了这个接口的订阅者,就会接收到发布的消息(执行的操作)
using System;
using System.Collections.Generic;
using System.Timers;
namespace ConsoleApp1
{
class Program
{
interface INewspaper {
void SetNewspaper(Newspaper newspaper);
void ReadNewspaper();
}
class Company:INewspaper
{
public string Name { get; set; }
public Company(string name) { this.Name = name; }
public Newspaper Newspaper { get; set; }
public void SetNewspaper(Newspaper newspaper)
{
this.Newspaper = newspaper;
}
public void ReadNewspaper()
{
Console.WriteLine("公司{0}正在读报纸 {1}标题是 {2} 出版社{3}", this.Name, this.Newspaper.Title, this.Newspaper.Content, this.Newspaper.PublisherName);
}
}
class Person : INewspaper {
public string Name { get; set; }
public Person(string name) { this.Name = name; }
public Newspaper Newspaper { get; set; }
public void SetNewspaper(Newspaper newspaper) {
this.Newspaper = newspaper; }
public void ReadNewspaper() {
Console.WriteLine("{0}正在读报纸 {1}标题是 {2} 出版社{3}", this.Name,this.Newspaper.Title, this.Newspaper.Content,this.Newspaper.PublisherName);
}
}
class Newspaper {
string title;
string content;
public string PublisherName { get; set; }
public string Title { get; set; }
public string Content { get; set; }
}
class Publisher {
public string Name { get; set;}
public Publisher(string name) {
this.Name = name;
}
public List<INewspaper> subscribers = new List<INewspaper>();
public void SendNewspaper(Newspaper newspaper) {
newspaper.PublisherName = this.Name;
subscribers.ForEach(subscriber => { subscriber.SetNewspaper(newspaper); subscriber.ReadNewspaper(); });
}
}
static void Main(string[] args)
{
var publisher = new Publisher("出版社X");
publisher.subscribers.Add(new Person("a"));
publisher.subscribers.Add(new Person("b"));
publisher.subscribers.Add(new Person("c"));
publisher.subscribers.Add(new Company("a"));
publisher.subscribers.Add(new Company("b"));
publisher.subscribers.Add(new Company("c"));
publisher.SendNewspaper(new Newspaper() { Title="标题",Content="内容" });
}
}
}
C#方式的订阅/发布模式
using System;
using System.Collections.Generic;
using System.Timers;
namespace ConsoleApp1
{
class Program
{
class Company
{
public string Name { get; set; }
public Company(string name) { this.Name = name; }
public Newspaper Newspaper { get; set; }
public void SetNewspaper(Newspaper newspaper)
{
this.Newspaper = newspaper;
}
public void ReadNewspaper()
{
Console.WriteLine("公司{0}正在读报纸 {1}标题是 {2} 出版社{3}", this.Name, this.Newspaper.Title, this.Newspaper.Content, this.Newspaper.PublisherName);
}
}
class Person {
public string Name { get; set; }
public Person(string name) { this.Name = name; }
public Newspaper Newspaper { get; set; }
public void SetNewspaper(Newspaper newspaper) {
this.Newspaper = newspaper; }
public void ReadNewspaper() {
Console.WriteLine("{0}正在读报纸 {1}标题是 {2} 出版社{3}", this.Name,this.Newspaper.Title, this.Newspaper.Content,this.Newspaper.PublisherName);
}
}
class Newspaper {
string title;
string content;
public string PublisherName { get; set; }
public string Title { get; set; }
public string Content { get; set; }
}
class Publisher {
public string Name { get; set; }
public Publisher(string name) {
this.Name = name;
}
/*
*
*
*
* //声明委托
* public delegate void _Subscribers(Newspaper newspaper);
* //委托属性
* public _Subscribers Subscribers { get;set;}
*
* */
// 委托 Action 简化
public Action<Newspaper> Subscribers;
//发布,通知,广播
public void SendNewspaper(Newspaper newspaper) {
newspaper.PublisherName = this.Name;
Subscribers(newspaper);
}
}
static void Main(string[] args)
{
var publisher = new Publisher("出版社X");
Person Aperson = new Person("A");
Person Bperson = new Person("B");
Company companyA = new Company("CompanyA");
Company companyB = new Company("CompanyB");
publisher.Subscribers = Aperson.SetNewspaper;//订阅,注册
publisher.Subscribers -= Aperson.SetNewspaper;//退订,取消注册
publisher.Subscribers += Bperson.SetNewspaper;//委托链
publisher.Subscribers += companyA.SetNewspaper;
publisher.Subscribers += companyB.SetNewspaper;
publisher.SendNewspaper(new Newspaper() { Title="标题",Content="内容" });
companyA.ReadNewspaper(); } }
}
C#中的Event来优化以上程序存在的BUG
事件
在C#中通过事件来描述对象或类间的动作协调和信息传递,在JAVA中也存在这一机制(swing,AWT,Android 等客户端编程),只不过JAVA中的事件都是通过接口实现而没有委托这种数据类型。
事件模型的五个组成部分
1,事件的拥有者(event source,对象)
2, 事件成员(event,成员)
3,事件的响应者(event subscriber,对象)
4,事件处理器(event handler,成员)-------本质上是一个回调方法
5,事件订阅--把事件处理器与事件关联在一起,本质上是一种以委托类型 为基础的“约定”
using System;
using System.Collections.Generic;
using System.Timers;
namespace ConsoleApp1
{
class Program
{
class PublisherArgs : System.EventArgs {
public PublisherArgs(Newspaper newspaper) {
this.Newspaper = newspaper;
}
public Newspaper Newspaper { get; set;}
}
class Company
{
public string Name { get; set; }
public Company(string name) { this.Name = name; }
public Newspaper Newspaper { get; set; }
public void SetNewspaper(object sender, PublisherArgs publisherArgs)
{
if (sender is Publisher)
{
publisherArgs.Newspaper.PublisherName = (sender as Publisher).Name;
}
this.Newspaper = publisherArgs.Newspaper;
}
public void ReadNewspaper()
{
Console.WriteLine("公司{0}正在读报纸 {1}标题是 {2} 出版社{3}", this.Name, this.Newspaper.Title, this.Newspaper.Content, this.Newspaper.PublisherName);
}
}
class Person {
public string Name { get; set; }
public Person(string name) { this.Name = name; }
public Newspaper Newspaper { get; set; }
public void SetNewspaper(object sender, PublisherArgs publisherArgs) {
if (sender is Publisher) {
publisherArgs.Newspaper.PublisherName = (sender as Publisher).Name;
}
this.Newspaper = publisherArgs.Newspaper;
}
public void ReadNewspaper() {
Console.WriteLine("{0}正在读报纸 {1}标题是 {2} 出版社{3}", this.Name,this.Newspaper.Title, this.Newspaper.Content,this.Newspaper.PublisherName);
}
}
class Newspaper {
string title;
string content;
public string PublisherName { get; set; }
public string Title { get; set; }
public string Content { get; set; }
}
class Publisher {
public string Name { get; set; }
public Publisher(string name) {
this.Name = name;
}
/*
*
*
*
* //声明委托
* public delegate void _Subscribers(Newspaper newspaper);
* //委托属性
* public _Subscribers Subscribers { get;set;}
*
* */
// 委托 Action 简化
//public event Action<object,Newspaper> Subscribers=null;
//EventHandler 事件处理器
public event EventHandler<PublisherArgs> Subscribers = null;
//发布,通知,广播
public void SendNewspaper(Newspaper newspaper) {
newspaper.PublisherName = this.Name;
if (Subscribers !=null) {
foreach (Action<object, PublisherArgs> handler in Subscribers.GetInvocationList()) {
try {
handler(this, new PublisherArgs(newspaper));
} catch(ApplicationException ex) {
Console.WriteLine(ex.Message);
} } }
} }
static void Main(string[] args)
{
var publisher = new Publisher("出版社X");
Person Aperson = new Person("A");
Person Bperson = new Person("B");
Company companyA = new Company("CompanyA");
Company companyB = new Company("CompanyB");
publisher.Subscribers += Aperson.SetNewspaper;//订阅,注册
publisher.Subscribers -= Aperson.SetNewspaper;//退订,取消注册
publisher.Subscribers += Bperson.SetNewspaper;//委托链
publisher.Subscribers += (n,ex) => { throw new ApplicationException("have an erro"); };
publisher.Subscribers += companyA.SetNewspaper;
publisher.Subscribers += companyB.SetNewspaper;
publisher.SendNewspaper(new Newspaper() { Title="标题",Content="内容" });
companyB.ReadNewspaper();
} }
}
泛型
C#中的泛型与JAVA中的泛型一模一样。因此直接略过了
ArrayList
C#中arrylist与JAVA中的arrylist 用法基本一致,常规操作如下:
using System;
using System.Threading;
using UserNamespace;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UserNamespace.Studnet;
using System.Collections;
namespace ConsoleApp1
{
class Program
{
public static void ListOperation(ArrayList list) {
//增,可以添加任意类型的元素
list.Add(1);
list.Add("hello world");
list.Add(3.14);
list.Add(true);
list.AddRange(list);
//批量添加,讲一个集合添加到另外一个集合中
list.AddRange(new int[] {1,2,3,4,5});
list.Add(new int[] { 1, 2, 3, 4, 5 });
Console.WriteLine(list.Count);
//移除指定位置,第一个元素是 1
list.Remove(1);
//移除指定下标的元素从0开始
list.RemoveAt(0);
//从起点开始,移除多少个元素
list.RemoveRange(0, 2);
//指定下标修改元素
list[2] = true;
//2,批量修改元素
list.SetRange(0,new string[] {"a","b","c","d" });
//for-each 遍历集合中的元素
foreach (object obj in list) {
Console.WriteLine(obj); }
//通过枚举器遍历集合
IEnumerator ienum = list.GetEnumerator();
while (ienum.MoveNext()) {
object obj = ienum.Current;
Console.WriteLine(obj); }
int index1 = list.IndexOf(3);//查询某个元素第一次出现的下标
int index2 = list.LastIndexOf(3);//查询某个元素最后一次出现的下标
int index3 = list.BinarySearch(3);//通过二分法查找某个元素的下标
//集合排序,默认升序
list.Sort();
//集合翻转
list.Reverse();
//集合中是否包含某个元素
list.Contains(1);
//集合拷贝
object[] newList = new object[20];
list.CopyTo(newList);
//集合中插入元素
list.Insert(0,"hello world");
//集合中批量插入元素
list.InsertRange(1,new bool[3]{ false,true,false}); }
static void Main(string[] args)
{
ArrayList list = new ArrayList();
ListOperation(list);
} }}
arrylist自定义排序
当对对象进行排序的时候,需要实现一个接口 IComparable 或 IComparable<T> 来定义一个比较规则,然后再进行比较即可。
using System;
using System.Threading;
using UserNamespace;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UserNamespace.Studnet;
using System.Collections;
namespace ConsoleApp1
{
class Person :IComparable{
int age;
public Person(int age)
{
this.age = age;
}
//IComparable 接口中的定义比较规则
// =0 this==obj
// >0 this > obj
// <0 this < obj
public int CompareTo(object obj)
{
if (obj is Person) {
Person anotherperson = obj as Person;
return this.age - anotherperson.age;
}
return 0;
}
public override string ToString()
{
return this.age + " ";
}
}
class Program
{
public static void ListOperation(ArrayList list) {
//增,可以添加任意类型的元素
list.Add(1);
list.Add("hello world");
list.Add(3.14);
list.Add(true);
list.AddRange(list);
//批量添加,讲一个集合添加到另外一个集合中
list.AddRange(new int[] {1,2,3,4,5});
list.Add(new int[] { 1, 2, 3, 4, 5 });
Console.WriteLine(list.Count);
//移除指定位置,第一个元素是 1
list.Remove(1);
//移除指定下标的元素从0开始
list.RemoveAt(0);
//从起点开始,移除多少个元素
list.RemoveRange(0, 2);
//指定下标修改元素
list[2] = true;
//2,批量修改元素
list.SetRange(0,new string[] {"a","b","c","d" });
//for-each 遍历集合中的元素
foreach (object obj in list) {
Console.WriteLine(obj);
}
//通过枚举器遍历集合
IEnumerator ienum = list.GetEnumerator();
while (ienum.MoveNext()) {
object obj = ienum.Current;
Console.WriteLine(obj);
}
int index1 = list.IndexOf(3);//查询某个元素第一次出现的下标
int index2 = list.LastIndexOf(3);//查询某个元素最后一次出现的下标
int index3 = list.BinarySearch(3);//通过二分法查找某个元素的下标
//集合排序,默认升序
list.Sort();
//集合翻转
list.Reverse();
//集合中是否包含某个元素
list.Contains(1);
//集合拷贝
object[] newList = new object[20];
list.CopyTo(newList);
//集合中插入元素
list.Insert(0,"hello world");
//集合中批量插入元素
list.InsertRange(1,new bool[3]{ false,true,false});
}
static void Main(string[] args)
{
ArrayList list = new ArrayList();
list.Add(new Person(20));
list.Add(new Person(2));
list.Add(new Person(6));
list.Add(new Person(7));
list.Add(new Person(12));
list.Add(new Person(28));
list.Sort();
IEnumerator ienum = list.GetEnumerator();
while (ienum.MoveNext()){
object obj = ienum.Current;
Console.WriteLine(obj);
} }
List 集合
C# 的list集合与JAVA的list集合 基本相同,用法如下:
using System;
using System.Threading;
using UserNamespace;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UserNamespace.Studnet;
using System.Collections;
namespace ConsoleApp1
{
class Person :IComparable{
int age;
public Person(int age)
{
this.age = age;
}
//IComparable 接口中的定义比较规则
// =0 this==obj
// >0 this > obj
// <0 this < obj
public int CompareTo(object obj)
{
if (obj is Person) {
Person anotherperson = obj as Person;
return this.age - anotherperson.age;
}
return 0;
}
public override string ToString()
{
return this.age + " ";
}
}
class Program
{
public static void ListOperation(List<string> list) {
//增,可以添加任意类型的元素
list.Add("hello world");
list.Add("hello world 1");
list.Add("hello world 2");
list.AddRange(list);
//批量添加,讲一个集合添加到另外一个集合中
list.AddRange(new string[] {"1 asd","2 aaa","3 hello"});
Console.WriteLine(list.Count);
//移除指定位置,第一个元素是 1
list.Remove(1);
//移除指定下标的元素从0开始
list.RemoveAt(0);
//从起点开始,移除多少个元素
list.RemoveRange(0, 2);
list.RemoveAll(name=>name== "hello world");
//指定下标修改元素
list[2] = "xiugai";
//获取一个集合中的子集
List<string> sub = list.GetRange(1,2);
//exists 判断集合中是否存在满足指定条件的元素
//contains 判断集合中是否包含指定元素
bool result = list.Exists(name=>name=="hello");
Console.WriteLine(result);
//寻找集合中匹配的一项
string oneString = list.Find( name => name == "hello");
Console.WriteLine(oneString);
//寻找集合中所有匹配项
List<string> manyString = list.FindAll(name => name == "hello");
//查询符合条件的第一个元素的下标
int indexF =list.FindIndex(name => name == "hello");
//查询符合条件的最后一个元素
string lastElemet = list.FindLast(name => name == "hello");
//查询符合条件的最后一个元素的下标
int lastElemetIndex = list.FindLastIndex(name => name == "hello");
//移除符合条件的所有元素
list.RemoveAll(name => name == "hello");
//for-each 遍历集合中的元素
foreach (object obj in list) {
Console.WriteLine(obj);
}
//通过枚举器遍历集合
IEnumerator ienum = list.GetEnumerator();
while (ienum.MoveNext()) {
object obj = ienum.Current;
Console.WriteLine(obj);
}
int index1 = list.IndexOf("3");//查询某个元素第一次出现的下标
int index2 = list.LastIndexOf("hello");//查询某个元素最后一次出现的下标
//集合排序,默认升序
list.Sort();
//集合翻转
list.Reverse();
//集合中是否包含某个元素
list.Contains(1);
//集合拷贝
object[] newList = new object[20];
}
static void Main(string[] args)
{
List<string> list = new List<string>();
ListOperation(list);
}}}
栈和队列
在C#里面封装了stack数据结构,stack 的特点是先进后出,基本操作如下:
static void Main(string[] args)
{
//栈
Stack stack = new Stack();
stack.Push("first");
stack.Push("second");
stack.Push("third");
//获取栈顶元素
Object ele = stack.Peek();
Console.WriteLine(ele);
//出栈
Object popEle = stack.Pop();
Console.WriteLine(popEle);
//遍历
foreach (object obj in stack) {
Console.WriteLine(obj);
}
在C#里面封装了Queue数据结构,Queue 的特点是先进先出,基本操作如下:
//队列
Queue queue = new Queue();
queue.Enqueue("first");
queue.Enqueue("second");
queue.Enqueue("third");
//获取队列首个元素
Object obj1 = queue.Peek();
Console.WriteLine(obj1);
//将队首元素移除队列,返回值为刚刚移除的元素
object obj2 = queue.Dequeue();
Console.WriteLine(obj2);
//遍历
foreach (object obj in queue)
{
Console.WriteLine(obj);
}
HashTable
hashtable 是一种存取键值对的集合,在C#里面,hashtable是栈结构并且,元素是DictionaryEntry,具体操作如下:
using System;
using System.Threading;
using UserNamespace;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UserNamespace.Studnet;
using System.Collections;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
//实例化一个HashTable
Hashtable table = new Hashtable();
//增
table.Add("key1","value");
table.Add("key2", "value");
table["key2"] = "修改了哦";
table.Add("key3", "value");
//获取所有key
ICollection keys = table.Keys;
//先进后出
foreach (DictionaryEntry tempDictionary in table) {
Console.WriteLine(tempDictionary.Key+" "+ tempDictionary.Value);
}
table.Remove("key2");
//通过所有key获取value
foreach (string tempstr in keys) {
Console.WriteLine(tempstr);
} } }}
Dictionary
Dictionary是一种键值对集合,但是和hashtable的不一样的地方在于hastable在于元素的类型不需要一开始就强制声明,而Dictionary必须声明键与值的类型。具体操作如下:
using System;
using System.Threading;
using UserNamespace;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UserNamespace.Studnet;
using System.Collections;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Dictionary<string,string> tempDictionary = new Dictionary<string, string>();
//增加元素
tempDictionary.Add("key1","hello");
tempDictionary.Add("key2", "hello1");
//按照键删除元素
tempDictionary.Remove("key1");
//修改元素
tempDictionary["key1"]= "修改了";
foreach (Object obj in tempDictionary) {
Console.WriteLine(obj);
}
foreach (KeyValuePair<string,string> obj in tempDictionary)
{
Console.WriteLine(obj.Key+" "+obj.Value);
}
//通过获取所有key来遍历
ICollection keys = tempDictionary.Keys;
foreach (string tempstr in keys)
{
Console.WriteLine(tempstr);
}
}
}
正则表达式
所有语言的正则表达式都是通用的,就不多介绍了,具体操作如下:
using System;
using System.Threading;
using UserNamespace;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using UserNamespace.Studnet;
using System.Collections;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
//^:匹配一个字符串的开头
//$:匹配一个字符的结尾
//实例化一个正则表达式的对象
Regex regex = new Regex("^hello$");
bool checkA = regex.IsMatch("hello");
Console.WriteLine(checkA);
regex = new Regex("hello");
checkA = regex.IsMatch("hello world");
Console.WriteLine(checkA);
//[]:匹配一个字符,这一位字符可以是这个括号中的任何一个
regex = new Regex("[qwhe]llo");
checkA = regex.IsMatch("hello world");
Console.WriteLine(checkA);
regex = new Regex("^[qwhe]llo$");
checkA = regex.IsMatch("hello world");
Console.WriteLine(checkA);
//[1-9]:匹配任何一个数字
regex = new Regex("^[1-9]llo world$");
checkA = regex.IsMatch("1ello world");
Console.WriteLine(checkA);
//[A-Za-z]:匹配任何一个字母
regex = new Regex("^[A-Za-z]llo world$");
checkA = regex.IsMatch("aello world");
Console.WriteLine(checkA);
//[A-Za-z0-9]:匹配任何一个字母和数字
regex = new Regex("^[A-Za-z]llo world$");
checkA = regex.IsMatch("1ello world");
Console.WriteLine(checkA);
//[^1-9] 表示这一位字符可以是[1,9] 之外的任何字符
regex = new Regex("^1-9");
checkA = regex.IsMatch("8");
Console.WriteLine(checkA);
//+:表示前面的一位字符表示了1次或多次
regex = new Regex("^1+");
checkA = regex.IsMatch("1111lo");
Console.WriteLine(" + :"+checkA);
//*:表示前面的一位字符表示了0次或多次
regex = new Regex("^1*");
checkA = regex.IsMatch("ok");
Console.WriteLine(" * :" + checkA);
//?:表示前面的一位字符表示了0次或1次
regex = new Regex("^1?");
checkA = regex.IsMatch("11111ok");
Console.WriteLine(" ? :" + checkA);
//{m}:前面的一位字符连续出现了m次
regex = new Regex("^1{5}");
checkA = regex.IsMatch("11111ok");
Console.WriteLine("{m} :" + checkA);
//{m,}:前面的一位字符至少连续出现了m次
regex = new Regex("^1{1,}");
checkA = regex.IsMatch("11111ok");
Console.WriteLine("{m,} :" + checkA);
//{m,n}:前面的一位字符连续出现了m到n次
regex = new Regex("1{2,6}");
checkA = regex.IsMatch("11111ok");
Console.WriteLine("{m,n} :" + checkA);
// \d :等价[0-9] 判断前面的一位字符是否为数字
// \D:等价[^0-9] 判断前面的一位字符是否为非数字
//.: 通配符,可以匹配任意字符
//判断一个手机号是否为合法的
bool checkphonenumber = Regex.IsMatch("13666669999","^1[35789]\\d{9}$");
Console.WriteLine("checkphonenumber :" + checkphonenumber);
//判断一个邮箱号是否为合法的
bool checkemail = Regex.IsMatch("13666669999@qq.com", "^.+@.+[\\.]com$");
Console.WriteLine("checkemail :" + checkemail);
//替换字符串为逗号 Regex.Replace可以实现批量替换
string tempstr =Regex.Replace("lily zhang,jhon,key"," {2,}",",");
Console.WriteLine("tempstr :" + tempstr);
//():表示分组
//屏蔽手机号中间四位为*
string phone = "13666669999";
string parttern = "^(1[35789][0-9])(\\d{4})(\\d{4})$";
//获取每一个分组的字符串
Match match = Regex.Match(phone, parttern);
GroupCollection groups = match.Groups;//获取所有分组
string group1 = groups[1].Value;
string group2 = groups[2].Value;
string group3 = groups[3].Value;
Console.WriteLine("phone:"+ group1+"****" + group3);
Console.WriteLine("tempstr :" + tempstr);
string qqNumber = "62346";
//判断QQ号的规则逻辑
//正则表达式 以1到9开始的第一个数字,后面是4到10位的数字
bool check =Regex.IsMatch(qqNumber,"^[1-9]\\d{4,10}$");
Console.WriteLine(check); } }}
总结
第二天结束了,依然有一点没有完全学习完C#的基础语法部分,但是也快了,估计明天就能学习完了,洗洗睡了先。估计明天就能开始学习unity了。