using的使用
1.引用命名空间
语法结构为using+命名空间名字或者项目名
using System;
2.为命名空间或类型创建别名
3.using作为语句使用
using(){}
静态成员:
- 属于类:静态成员属于类本身,而不是类的任何特定实例。
- 使用类名调用:可以通过类名直接访问静态成员,而不需要创建类的实例。
- 在实例化前可用:静态成员在类的任何实例被创建之前就可以使用。
- 不能访问非静态成员:静态方法不能直接访问类的非静态成员,因为非静态成员需要一个类的实例来存在。
- 常用于工具类:静态成员常用于工具类或实用程序类,提供一组相关功能,而不需要类的实例。
非静态成员:
- 属于实例:非静态成员属于类的一个特定实例。
- 使用实例访问:必须先创建类的实例,然后通过这个实例来访问非静态成员。
- 在实例化后可用:非静态成员在类的实例被创建之后才能使用。
- 可以访问静态和非静态成员:非静态方法可以访问类的静态和非静态成员。
- 实现面向对象的特性:非静态成员允许类实现封装、继承和多态等面向对象的特性。
LINQ快速查询
List<int> numbers = new List<int> { 1, 3, 7, 2, 9, 4, 6, 8, 5 };
var result = from n in numbers
where n > 5
orderby n descending
select n;
foreach (var n in result)
{
Console.WriteLine(n);
}
nameof() 获取对应变量的变量名;
Date date = new Date(){ID=19,Name = "你"};
textbox1.DataBindings.Add("Text", data, nameof(data.Name));
winform OpenFileDialog控件
OpenFileDialog openDlg = new OpenFileDialog();
// 指定打开文本文件(后缀名为txt)
openDlg.Filter = "文本文件|*.txt" ;
if (openDlg.ShowDialog() == DialogResult.OK)
{
// 读出文本文件的所以行
string [] lines = File.ReadAllLines(openDlg.FileName);}
Type类
Type 是每个类都默认有的type类,可以通过type来访问程序集中的一些信息,也就是反射
比如说有一个类叫 Class1
Type ty = typeof(Class1); //来获取程序集中的信息
ty.Name 获取的是类名
ty.NameSpace 获取的是命名空间
ty.Assembly 获取程序集中非私有字段的名
FieldInfo[] info1 = ty.GetFields(); 获取字段名的集合
PropertyInfo[] infor2 = ty.GetProperties(); 获取属性的名的集合
MethodInfo[] infor3 = ty.GetMothods();获取方法名的集合
还有一种获取type对象
Class2 class2 = new Class2();
Type ts = class2.GetType();也能获取type对象
因为每个类都只有一个type对象
Assembly类
Assembly ax = Assembly.Load("程序集名");加载程序集会自动查找程序集
Assembly ex = Assembly.FormLoad("程序集所处路径");他不会搜索其他位置
绑定基类
绑定数据类必须实现INotifyPropertyChanged接口,否则数据类属性的变更无法实时刷新到界面,但可以从界面刷新到类。
为了方便,我们设计一个绑定基类:
/// <summary>
/// 数据绑定基类
/// </summary>
public abstract class BindableBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected bool SetProperty<T>(ref T field, T newValue, [CallerMemberName] string propertyName = null)
{
if (!EqualityComparer<T>.Default.Equals(field, newValue))
{
field = newValue;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
return true;
}
return false;
}
}
需要绑定的数据类继承绑定基类即可:
/// <summary>
/// 数据类
/// </summary>
public class Data : BindableBase
{
private int id = 0;
private string name = string.Empty;
public int ID { get => id; set => SetProperty(ref id, value); }
public string Name { get => name; set => SetProperty(ref name, value); }
}
功能扩展
主要为绑定基类扩展了以下两个功能:
- 获取属性的Description特性内容
- 从指定类加载属性值,对象直接赋值是赋值的引用,控件绑定的数据源还是之前的对象
这两个功能不属于绑定基类的必要功能,但可以为绑定提供方便,所以单独放在扩展方法类里面。
代码如下:
/// <summary>
/// 数据绑定基类的扩展方法
/// </summary>
public static class BindableBaseExtension
{
/// <summary>
/// 获取属性的描述,返回元组格式为 Item1:描述信息 Item2:属性名称
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public static Tuple<string, string>[] GetDescription(this BindableBase bindData)
{
var proAry = bindData.GetType().GetProperties();
var desAry = new Tuple<string, string>[proAry.Length];
string desStr;
for (int i = 0; i < proAry.Length; i++)
{
var attrs = (DescriptionAttribute[])proAry[i].GetCustomAttributes(typeof(DescriptionAttribute), false);
desStr = proAry[i].Name;
foreach (DescriptionAttribute attr in attrs)
{
desStr = attr.Description;
}
desAry[i] = Tuple.Create(desStr, proAry[i].Name);
}
return desAry;
}
/// <summary>
/// 加载同类型指定对象的属性值,如果当前属性值或目标属性值为null则不执行赋值操作
/// </summary>
/// <param name="data"></param>
public static void Load(this BindableBase source, BindableBase dest)
{
if (source == null || dest == null)
{
//不执行操作
return;
}
Type type = source.GetType();
if (type != dest.GetType())
{
throw new ArgumentNullException("参数类型不一致");
}
var proAry = type.GetProperties();
for (int i = 0; i < proAry.Length; i++)
{
var proType = proAry[i].PropertyType;
if (proType.IsSubclassOf(typeof(BindableBase)))
{
//检测到内部嵌套的绑定基类,建议不处理直接跳过,这种情况应该单独处理内嵌对象的数据加载
//var childData = (BindableBase)(proAry[i].GetValue(source));
//childData.Load((BindableBase)(proAry[i].GetValue(dest)));
}
else
{
proAry[i].SetValue(source, proAry[i].GetValue(dest));
}
}
}
}
简单控件绑定
简单属性绑定是指某对象属性值和某控件属性值之间的简单绑定,需要了解以下内容:
- Control.DataBindings 属性:代表控件的数据绑定的集合。
- Binding 类:代表某对象属性值和某控件属性值之间的简单绑定。
使用方法如下:
Data data = new Data() { ID=1,Name="test"};
//常规绑定方法
textBox1.DataBindings.Add("Text", data, "ID");
//使用这种方式避免硬编码
textBox2.DataBindings.Add("Text", data, nameof(data.Name));
注:这种绑定会自动处理字符串到数据的类型转换,转换失败会自动恢复原值。
列表控件绑定
列表控件绑定主要用于 ListBox 与 ComboBox 控件,它们都属于 ListControl 类的派生类。ListControl 类为 ListBox 类和 ComboBox 类提供一个共同的成员实现方法。
注:CheckedListBox 类派生于 ListBox 类,不再单独说明。
使用列表控件绑定前,需要了解以下内容:
-
ListControl.DataSource 属性:获取或设置此 ListControl 的数据源,值为实现 IList 或 IListSource 接口的对象,如 DataSet 或 Array。
-
ListControl.DisplayMember 属性:获取或设置要为此 ListControl 显示的属性,指定 DataSource 属性指定的集合中包含的对象属性的名称,默认值为空字符串("")。
-
ListControl.ValueMember 属性:获取或设置属性的路径,它将用作 ListControl 中的项的实际值,表示 DataSource 属性值的单个属性名称,或解析为最终数据绑定对象的属性名、单个属性名或句点分隔的属性名层次结构, 默认值为空字符串("")。
注:最终的选中值只能通过ListControl.SelectedValue 属性获取,目前还没找到可以绑定到数据的方法。
绑定BindingList集合
BindingList是一个可用来创建双向数据绑定机制的泛型集合,使用方法如下:
BindingList<Data> list = new BindingList<Data>();
list.Add(new Data() { ID = 1, Name = "name1" });
list.Add(new Data() { ID = 2, Name = "name2" });
comboBox1.DataSource = list;
comboBox1.ValueMember = "ID";
comboBox1.DisplayMember = "Name";
注:如果使用List泛型集合则不支持双向绑定。同理,如果Data没有继承绑定基类,则属性值的变更也不会实时更新到界面。
绑定DataTable表格
DataTable支持双向绑定,使用方法如下:
DataTable dt = new DataTable();
DataColumn[] dcAry = new DataColumn[]
{
new DataColumn("ID"),
new DataColumn("Name")
};
dt.Columns.AddRange(dcAry);
dt.Rows.Add(1, "name1Dt");
dt.Rows.Add(2, "name2Dt");
comboBox1.DataSource = dt;
comboBox1.ValueMember = "ID";
comboBox1.DisplayMember = "Name";
绑定BindingSource源
BindingSource 类封装窗体的数据源,旨在简化将控件绑定到基础数据源的过程,详细内容可查看 BindingSource 组件概述。
有时候数据类型可能没有实现INotifyPropertyChanged接口,并且这个数据类型我们还修改不了,这种情况就只能使用BindingSource来将控件绑定到数据了。
假设Data类没有继承BindableBase,绑定方法如下:
List<Data> list = new List<Data>();
list.Add(new Data() { ID = 1, Name = "name1" });
list.Add(new Data() { ID = 2, Name = "name2" });
BindingSource bs = new BindingSource();
bs.DataSource = list;
comboBox1.DataSource = bs;
comboBox1.ValueMember = "ID";
comboBox1.DisplayMember = "Name";
关键是下面的步骤,改变集合内容时手动触发变更:
//单项数据变更
list[0].Name = "test";
bs.ResetItem(0);
//添加数据项
list.Add(new Data() { ID = 3, Name = "name3" });
bs.ResetBindings(false);
//在BindingSource上添加或使用BindingList列表,则可以不用手动触发变更通知
bs.Add(new Data() { ID = 4, Name = "name4" });
表格控件绑定
绑定DataTable
方法如下:
DataColumn c1 = new DataColumn("ID", typeof(string));
DataColumn c2 = new DataColumn("名称", typeof(string));
dt.Columns.Add(c1);
dt.Columns.Add(c2);
dt.Rows.Add(11, 22);
//禁止添加行,防止显示空白行
dataGridView1.AllowUserToAddRows = false;
//选择是否自动创建列
dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = dt.DefaultView;
绑定BindingList
方法如下:
//填充数据
BindingList<Data> dataList = new BindingList<Data>();
for (int i = 0; i < 5; i++)
{
dataList.Add(new Data() { ID = i, Name = "Name" + i.ToString() });
}
//禁止添加行,防止显示空白行
dataGridView1.AllowUserToAddRows = false;
//选择是否自动创建列
dataGridView1.AutoGenerateColumns = false;
//手动创建列
var desAry = dataList[0].GetDescription();
int idx = 0;
foreach (var des in desAry)
{
idx = dataGridView1.Columns.Add($"column{idx}", des.Item1); // 手动添加某列
dataGridView1.Columns[idx].DataPropertyName = des.Item2; // 设置为某列的字段
}
//绑定集合
dataGridView1.DataSource = dataList;
//集合变更事件
dataList.ListChanged += DataList_ListChanged;
注:上面的GetDescription()是绑定基类的扩展方法。
BindingList提供集合的变更通知,Data通过继承绑定基类提供属性值的变更通知。
UI线程全局类
上面所有绑定的数据源都不支持非UI线程的写入,会引起不可预知的问题,运气好的话也不会报异常出来。
为了方便多线程情况下更新数据源,设计一个UIThread类封装UI线程SynchronizationContext的Post、Send的操作,用来处理所有的UI更新操作,关于SynchronizationContext可以参考SynchronizationContext 综述。
代码如下:
/// <summary>
/// UI线程全局类
/// </summary>
public static class UIThread
{
private static SynchronizationContext context;
/// <summary>
/// 同步更新UI控件的属性及绑定数据源
/// </summary>
/// <param name="act"></param>
/// <param name="state"></param>
public static void Send(Action<object> act, object state)
{
context.Send(obj=> { act(obj); }, state);
}
/// <summary>
/// 同步更新UI控件的属性及绑定数据源
/// </summary>
/// <param name="act"></param>
public static void Send(Action act)
{
context.Send(obj => { act(); }, null);
}
/// <summary>
/// 异步更新UI控件的属性及绑定数据源
/// </summary>
/// <param name="act"></param>
/// <param name="state"></param>
public static void Post(Action<object> act, object state)
{
context.Post(obj => { act(obj); }, state);
}
/// <summary>
/// 异步更新UI控件的属性及绑定数据源
/// </summary>
/// <param name="act"></param>
public static void Post(Action act)
{
context.Post(obj => { act(); }, null);
}
/// <summary>
/// 在UI线程中初始化,只取第一次初始化时的同步上下文
/// </summary>
public static void Init()
{
if (context == null)
{
context = SynchronizationContext.Current;
}
}
}
直接在主界面的构造函数里面初始化即可:
UIThread.Init();
使用方法如下:
Task.Run(() =>
{
//同步更新UI
UIThread.Send(() => { dataList.RemoveAt(0); });
});