三个类,其中B继承A
Code
1public class A
2
3{
4
5public A()
6
7{
8
9AName = "This is A";
10
11}
12
13public string AName { get; set; }
14
15}
16
17
18
19public class B : A
20
21{
22
23public B()
24
25{
26
27BName = "This is B";
28
29}
30
31public string BName { get; set; }
32
33}
34
35
36
37public class C
38
39{
40
41public C()
42
43{
44
45CName = "This is C";
46
47}
48
49public string CName { get;set;}
50
51}
52
1public class A
2
3{
4
5public A()
6
7{
8
9AName = "This is A";
10
11}
12
13public string AName { get; set; }
14
15}
16
17
18
19public class B : A
20
21{
22
23public B()
24
25{
26
27BName = "This is B";
28
29}
30
31public string BName { get; set; }
32
33}
34
35
36
37public class C
38
39{
40
41public C()
42
43{
44
45CName = "This is C";
46
47}
48
49public string CName { get;set;}
50
51}
52
测试用方法
Code
public static string GetName<T>(object obj) where T : A
{
return typeof(T).GetProperty("AName").GetValue(obj,null).ToString();
}
public static string GetName<T>(object obj) where T : A
{
return typeof(T).GetProperty("AName").GetValue(obj,null).ToString();
}
约束关系要求类型变量T是A本身或者继承自A
Code
A a = new A();
B b = new B();
C c = new C();
A a = new A();
B b = new B();
C c = new C();
此时可以用 GetName<A>(a)或者GetName<B>(b),如果调用GetName<C>(c)就会报错;
此外还可以使用where T:new()来指定构造函数