C#泛型与反射

正文

获取名为”MyClass”的类型

1
Type t = Type.GetType("MyClass");

或者

1
2
MyClass myclass = new MyClass();
Type t = myclass.GetType();

获取”MyClass”的属性

1
PropertyInfo[] properts = t.GetProperties();

获取属性名称

1
2
3
4
5
6
7
8
9
10
using System.Reflection;

Type t = obj.GetType();//获得该类的Type

foreach (PropertyInfo pi in t.GetProperties())
{
var name = pi.Name;//获得属性的名字,后面就可以根据名字判断来进行些自己想要的操作
var value = pi.GetValue(obj, null);//用pi.GetValue获得值
var type = value?.GetType() ?? typeof(object);//获得属性的类型
}

根据属性名获取某一属性

1
PropertyInfo p = t.GetProperty("Id");

设置某一属性的值

1
2
MyClass my = new MyClass();  
t.SetValue(my, 123, null);

应用:

1
2
3
4
5
6
7
8
9
10
public T Test<T>() where T: class, new()  
{
T t = new T();
PropertyInfo[] properts = t.GetType().GetProperties();
foreach(var item in properts)
{
item.setValue(t, "属性的值", null);
}
return t;
}