0%

C-Sharp-补课笔记-反射

前面啥也没有

示例

Interface

1
2
3
4
5
public interface InterfaceBase
{
public string Name { get; set; }
public void DoSomething();
}

Class1

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
public class Student : InterfaceBase
{
string name;

public string Name { get { return name; } set => this.name = value; }

public void DoSomething()
{
int i = 88;
Console.WriteLine("Write homework.");
}
}
class Worker : InterfaceBase
{
public string Name { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }

public void DoSomething()
{
Console.WriteLine("Working.");
}
}
class Cat
{
string name;
}

Class2

1
2
3
4
5
6
7
8
9
10
11
public class Teacher : InterfaceBase
{
string name;

public string Name { get { return name; } set => this.name = value; }

public void DoSomething()
{
Console.WriteLine("Teaching Math.");
}
}

TestClass

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
string dllPath = System.Environment.CurrentDirectory;
//加载路径下的文件
string[] files = Directory.GetFiles(dllPath);
foreach(string file in files)
{
if (!file.Contains(".dll"))//过滤
continue;
Assembly ass = Assembly.LoadFile(file);
Type[] types = ass.GetTypes();
object obj = null;
foreach (Type t in types)
{
// 判断类是否实现接口
if(typeof(InterfaceBase).IsAssignableFrom(t))
{
obj = ass.CreateInstance(t.FullName, true);
}
if (obj is InterfaceBase)//判断的另一种形式
{
InterfaceBase ib = obj as InterfaceBase;
ib.DoSomething();
}
}
}