反射是C#语言机制中获取动态对象属性的语言特性。
Reflection is a C# language mechanism for accessing dynamic object properties on runtime. Typically, reflection is used to fetch the information about dynamic object type and object attribute values. In REST application, for example, reflection could be used to iterate through serialized response object.
reference
https://stackoverflow.com/documentation/c%23/28/reflection#t=201708170100434986694
Get the members of a type
1 | using System; |
Get a method and invoke it
get a instance and invoke it
1 | using System; |
Get static method and invoke it
on the other hand, if the method is static, you do not need an instance to call it.1
2
3var method = typeof(Math).GetMethod('Exp');
var result = method.Invoke(null,new object[]{2})
// pass null as the first argument (no need for an instance)
partial 关键字
允许将一个类 结构 或者 接口放在几个不同的cs文件中。
适用于以下情况:
- 类型特别大,不宜放在一个文件中实现。
- 一个类型中的一部分为自动化工具生成的代码,不宜与我们自己编写的代码混合在一起。
- 需要多人合作编写的类。
局部类型是一个纯语言层的便已处理,不影响任何执行机制——C#编译器在编译的时候仍会将各个部分的局部类型合并成一个完整的类。1
2
3
4
5
6
7public partial class Program{
static void Main(){}
}
partial class Program{
publi void Test(){}
}
限制
- 局部类型只适用于类、接口、结构,不支持委托和枚举。
- 同一个类型的各个部分必须都有修饰符 partial。
- 使用局部类型时,一个类型的各个部分必须位于相同的命名空间中。
- 一个类型的各个部分必须被同时编译
局部类型的应用特性
在局部类型上的特性具有“累加”特性。