CSharp 基础知识

Last updated on 3 months ago

CSharp 基础知识

反射

类库列表

  • XLZF.DB.Interface
  • XLZF.DB.MySql
  • XLZF.DB.SqlServer
  • XLZF.Model
  • XLZF_KnowLedge

前提

1
2
3
4
5
6
7
8
//Interface
namespace XLZF.DB.Interface
{
public interface IDBhelper
{
void Query();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
namespace XLZF.DB.MySql
{
public class DBhelper : IDBhelper
{
public DBhelper()
{
Console.WriteLine("这里是{0}无参构造函数", this.GetType().FullName);
}

public void Query()
{
Console.WriteLine("这里是{0}的Query", this.GetType().FullName);
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
namespace XLZF.DB.SqlServer
{
public class DBhelper : IDBhelper
{
private static string ConnectionStringTesting = ConfigurationManager.ConnectionStrings["Business_Sqlserver"].ConnectionString;

public DBhelper()
{
Console.WriteLine("这里是{0}无参构造函数", this.GetType().FullName);
}

public void Query()
{
Console.WriteLine("这里是{0}的Query", this.GetType().FullName);
}

/// <summary>
/// 泛型
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public T QueryDomain<T>()
{
int id = 2;

/*

SELECT [Id]
,[Name]
,[Account]
,[Password]
,[Email]
,[Mobile]
,[CompanyId]
,[CompanyName]
,[State]
,[UserType]
,[LastLoginTime]
,[CreateTime]
,[Create_User_Id]
,[LastUpdate_User_Id]
,[LastUpdate_Datetime]
FROM [dbo].[User]

where Id= 2

*/

Type type = typeof(T);//找到分类

T t = (T)Activator.CreateInstance(type);//创建对象,这有一个强制转换

string columns = string.Join(",", type.GetProperties().Select(p => string.Format("[{0}]", p.Name)));//linq 把所有的属性替换成加[] 的字符串,并且以逗号分隔

string sql = string.Format("SELECT {0} from [{1}] where Id = {2}", columns, type.Name, id);

using (SqlConnection conn = new SqlConnection(ConnectionStringTesting))
{
SqlCommand command = new SqlCommand(sql, conn);

conn.Open();

SqlDataReader reader = command.ExecuteReader(System.Data.CommandBehavior.CloseConnection);//自动关闭

if (reader.Read())
{
foreach (var prop in type.GetProperties())
{
prop.SetValue(t, reader[prop.Name]);

Console.WriteLine("属性是{0}", prop.Name);
}

return t;
}
}

return default;
}
}
}

实体

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
namespace XLZF.Model
{
public class BaseModel
{
public int Id { get; set; }
}
}
namespace XLZF.Model
{
public class People
{
public int Id { get; set; }
public string Name { get; set; }
}
}
namespace XLZF.Model
{
public class User : BaseModel
{
public string Name { get; set; }

public string Account { get; set; }

public string Password { get; set; }

public string Email { get; set; }

public string Mobile { get; set; }

public int CompanyId { get; set; }

public string CompanyName { get; set; }

/// <summary>
/// 用户状态 0 正常 1 冻结 2 删除
/// </summary>
public int State { get; set; }

/// <summary>
/// 用户类型 1 普通用户 2 管理员 4 超级管理员
/// </summary>
public int UserType { get; set; }

public DateTime LastLoginTime { get; set; }

public DateTime CreateTime { get; set; }

public int Create_User_Id { get; set; }

public int LastUpdate_User_Id { get; set; }

public DateTime LastUpdate_Datetime { get; set; }
}
}

正菜

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
namespace XLZF_KnowLedge
{
/// <summary>
/// 1.依赖接口,进行可配置扩展
/// 2.不依赖接口,反射调用方法,包括私有方法,反射破坏单例
/// 3.通过反射查找model
/// </summary>
class Program
{
static void Main(string[] args)
{
#region 20180122 依赖接口,进行可配置扩展

//string nameSpace = ConfigurationManager.AppSettings["XLZF.DB.Interface.IDBhelper"];

//string[] namespaceArray = nameSpace.Split(',');

//Assembly assembly1 = Assembly.Load(namespaceArray[1]);//反射入口, 动态加载DLL

//Type type1 = assembly1.GetType(namespaceArray[0]);//基于类的完整名称 找出类型

//object oDBhelper = Activator.CreateInstance(type1);//根据类型,创建对象

//IDBhelper dbHelperRefletion = (IDBhelper)oDBhelper;//强转成接口类型

//dbHelperRefletion.Query();//调用方法

#endregion

#region 20180123 通过反射 需要DLL名称,类的名称,方法的名称来找到指定的方法调用成功

//Assembly assembly = Assembly.Load("XLZF.DB.SqlServer");//反射入口, 动态加载DLL

//Type type = assembly.GetType("XLZF.DB.SqlServer.ReflectionTest");//基于类的完整名称 找出类型

//object obj = Activator.CreateInstance(type);//根据类型创建对象

//foreach (MemberInfo method in type.GetMethods())
//{
// Console.WriteLine("名称:{0}", method.Name);
//}

//MethodInfo show1 = type.GetMethod("Show1");

//show1.Invoke(obj, null);//无参

//MethodInfo show2 = type.GetMethod("Show2");

//show2.Invoke(obj, new object[] { 11 });//有参,需要的是object数组


//MethodInfo show3 = type.GetMethod("Show3", new Type[] { });//无参,因为方法有重载,需要的是Type数组,为空

//show3.Invoke(obj, null);//无参

//MethodInfo show31 = type.GetMethod("Show3", new Type[] { typeof(int) });//有参,因为方法有重载,需要的是Type数组,typeof(int)

//show31.Invoke(obj, new object[] { 11 });//有参,需要的是object数组

//MethodInfo show32 = type.GetMethod("Show3", new Type[] { typeof(string) });//无参,因为方法有重载,需要的是Type数组,typeof(string)

//show32.Invoke(obj, new object[] { "11" });//有参,需要的是object数组

//MethodInfo show33 = type.GetMethod("Show3", new Type[] { typeof(int), typeof(string) });//无参,因为方法有重载,需要的是Type数组,typeof(int), typeof(string)

//show33.Invoke(obj, new object[] { 1, "11" });//有参,需要的是object数组

//MethodInfo show34 = type.GetMethod("Show3", new Type[] { typeof(string), typeof(int) });//无参,因为方法有重载,需要的是Type数组,typeof(string), typeof(int)

//show34.Invoke(obj, new object[] { "11", 1 });//有参,需要的是object数组


////当想调用这个类中的私有方法的时候,这么写。
//MethodInfo show4 = type.GetMethod("Show4", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);

//show4.Invoke(obj, new object[] { "11" });

////突破单例的私有构造函数
//Type typeSingle = assembly.GetType("XLZF.DB.SqlServer.Singleton");

//object objSingle = Activator.CreateInstance(typeSingle, true);//true 的意思是 是 私有方法

#endregion

#region 20180123 反射进阶 通过反射找到数据表中的字段,reader出对应的值,返回一个model

//正常写法
People people = new People();

people.Id = 1;

people.Name = "张三";

Console.WriteLine("people.Id={0} people.Name={1}", people.Id, people.Name);

//不走寻常路
Type type = typeof(People);//找到类型

object obj = Activator.CreateInstance(type);//创建对象

foreach (var prop in type.GetProperties())
{
if (prop.Name.Equals("Id"))
{
prop.SetValue(obj, 12);
}

if (prop.Name.Equals("Name"))
{
prop.SetValue(obj, "李四");
}

Console.WriteLine("属性名称是{0} 值是{1}", prop.Name, prop.GetValue(obj));
}

//更不走寻常路

DBhelper dBhelper = new DBhelper();

User user = dBhelper.QueryDomain<User>();

#endregion

Console.ReadKey();
}
}
}

Lambda

1.声明委托
2.实例化委托
3.调用委托
4.委托+lambda表达式应用:包括有返回值,无返回值,有参数,无参数
5.泛型委托 Action(无返回值) Func(有返回值,参数的最后一位)
6.linq + lambda表达式的应用

入口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
namespace XLZF_Lambda
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("XLZF_Lamda 学习测试");

My_lambda.Show();

Console.ReadLine();
}
}
}

方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
namespace XLZF_Lambda
{
public class My_lambda
{
//回顾委托
public delegate void Noreturn_void();//声明不带返回值不带参数的委托
public delegate string Noreturn_string();//声明无参数有返回值的委托
public delegate void Noreturn(string name);//声明委托
public delegate int Noreturn_Int(int x, int y);//声明有返回值的带参数的委托

//lambda就是一个方法,演化过程
public static void Show()
{
Console.WriteLine("委托咯~~~~");

#region 委托+lambda 表达式演化过程

Noreturn method = new Noreturn(Study);//实例化委托

method.Invoke("张三");//调用委托

Noreturn method1 = new Noreturn(
delegate (string name)
{
Console.WriteLine("{0}学习不停止", name);
});//基于匿名方法完成委托的实例化

method1.Invoke("张三");

Noreturn method2 = new Noreturn(
(string name) =>
{
Console.WriteLine("{0}学习不停止", name);
});//把delegate关键字去掉,换成=> 初步形成lambda表达式 => 的左边是参数列表,右边是方法体

method2.Invoke("张三");

Noreturn method3 = new Noreturn(
(name) =>
{
Console.WriteLine("{0}学习不停止", name);
});//lambda 表达式 =>左侧的参数类型去掉,因为实例化委托的时候必须满足委托的约束,当前委托的约束是无返回值,一个参数

method3.Invoke("张三");

//Noreturn method4 = Study;

Noreturn method4 =
(name) =>
{
Console.WriteLine("{0}学习不停止", name);
};//lambda 表达式 继续进化,去掉 new Noreturn() 因为委托本来就可以直接简写成 Noreturn method4= Study;

method4.Invoke("张三");

Noreturn method5 = (name) => Console.WriteLine("{0}学习不停止", name);
//lambda 表达式 继续进化,去掉 {};(大括号) 前提条件是:方法体只有一行

method5.Invoke("张三");

//最终
Noreturn method10 = (name) => Console.WriteLine("{0}学习不停止", name);//lambda示例 委托实例化

method10.Invoke("张三");

#endregion

#region 委托+lambda表达式练习

Noreturn_Int noreturn_Int = (x, y) => { return x + y; };//这是依据上面推到的方法写的

noreturn_Int.Invoke(1, 2);

Noreturn_Int noreturn_Int1 = (x, y) => x + y;//这是在上一行的基础上省略的写法,如果方法体只有一行可以 去掉return 还有大括号。

noreturn_Int1.Invoke(11, 22);

Noreturn_void noreturn_Void = () => { };//实例化该委托,这个委托没有返回值,没有参数

noreturn_Void.Invoke();

Noreturn_string noreturn_String = () => "1";//实例化委托,无参数,有返回值

noreturn_String.Invoke();

#endregion

#region 泛型委托,有这个泛型委托,也就是不用再特意的去声明一个委托了

//无返回值的用Action

Action act1 = () => { };

Action<string> act2 = s => { };
//最多16个参数
Action<int, string, Double, decimal, float, Action> act3 = (a, s, d, f, g, h) => { };

//有返回值的用Func
//最多16个参数
//参数的最后一位就是返回值类型
Func<string> fun = () => "123";

Func<string, int, Double, Func<decimal>, Action, decimal> fun1 = (a, s, d, f, g) => Convert.ToDecimal(12.22);

#endregion
}

/// <summary>
/// linq 结合 lambda表达
/// </summary>
public static void LinqShow()
{
List<int> intlist = new List<int>();

for (int i = 0; i < 100; i++)
{
intlist.Add(i);
}

//找出大于55的
foreach (int item in intlist.Where<int>(num => num > 55))
{
Console.WriteLine(item);
}
}

/// <summary>
/// 学习,很重要
/// </summary>
/// <param name="name"></param>
public static void Study(string name)
{
Console.WriteLine("{0}学习不停止", name);
}
}
}

面向对象编程

Object Oriented Programming

封装

继承

多态

参考资料:Dreamw

释义

  1. 通过继承实现的不同对象调用相同的方法,表现出不同的行为,称之为多态(简单明了)

  2. 允许将子类类型的指针赋值给父类类型的指针。也就是同一操作作用于不同的对象,可以有不同的解释,产生不同的执行结果。在运行时,可以通过指向基类的指针,来调用实现派生类中的方法。

优点

符合两种原则

  1. 里式替换原则(Liskov Substitution Principle):派生类(子类)能够被基类(父类)使用。通过父类new 子类。一致的类型,多个子类型可以被当成父类型来处理
  2. 开放封闭原则(Open Closed Principle):开放扩展,关闭修改。扩展的同时不动原有的逻辑。消除类型之间的耦合性

状态

多态性意味着有多重形式。在面向对象编程范式中,多态性往往表现为 “一个接口,多个功能“。

多态性可以是静态的或动态的。在静态多态性中,函数的响应是在编译时发生的。在动态多态性中,函数的响应是在运行时发生的。


CSharp 基础知识
http://example.com/2021/10/30/CSharp-基础知识/
Author
Harris
Posted on
October 30, 2021
Licensed under