C# 中反射的简单使用

本文最后更新于 2021年4月4日 晚上

C# 中关于反射的一个简单使用例子, 话不多说, 直接上代码.

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
using System;
using System.Reflection;

namespace ConsoleApp2
{
internal class Program
{
private static void Main(string[] args)
{
Type type = typeof(ImplicitlyDerivedFromObject);
BindingFlags flags = BindingFlags.Instance
| BindingFlags.Static
| BindingFlags.Public
| BindingFlags.NonPublic
| BindingFlags.FlattenHierarchy;
MemberInfo[] members = type.GetMembers(bindingAttr: flags);
Console.WriteLine($"Type of {type.Name} has {members.Length} members:");
foreach (var member in members)
{
string accss = "";
string stat = "";
var method = member as MethodBase;
if (method != null)
{
if (method.IsPublic)
{
accss = "Public";
}
else if (method.IsPrivate)
{
accss = "Private";
}
else if (method.IsFamily)
{
accss = "Protected";
}
else if (method.IsAssembly)
{
accss = "Internal";
}
else if (method.IsFamilyOrAssembly)
{
accss = "Protected Internal";
}
if (method.IsStatic)
{
stat = "Static";
}
}
var output = $"{member.Name} ({member.MemberType}): {accss} {stat}," +
$" Declared by {member.DeclaringType}";
Console.WriteLine(output);
}
Console.ReadLine();
}
}

public class ImplicitlyDerivedFromObject
{
}
}

C# 中反射的简单使用
https://blog.rayy.top/2018/09/14/2019-csharpReflection/
作者
貘鸣
发布于
2018年9月14日
许可协议