本人用C#在封装底层的时候需要获取属性,想到了用反射:
百度过后总结下
Type type = typeof(ContentInfo); //ContentInfo为类名
var memberInfos = type.GetProperties(); //可以获取ContentInfo所有属性,是个数组
通过遍历可得到各个属性
比如:foreach (var member in memberInfos)
而
type.GetProperty("Property1"); //获取指定名称的属性
另外,我在查资料的时候,看过这样一个例子,但是已经找不到它的原创了(十分对不起),可以复制建个控制台慢慢调试:
class Program
{
//单例测试
//定义类
public class MyClass
{
public int Property1 { get; set; }
}
static void Main()
{
MyClass tmp_Class = new MyClass();
tmp_Class.Property1 = 2;
Type type = tmp_Class.GetType(); //获取类型
System.Reflection.PropertyInfo propertyInfo = type.GetProperty("Property1"); //获取指定名称的属性
int value_Old = (int)propertyInfo.GetValue(tmp_Class, null); //获取属性值
Console.WriteLine(value_Old);
propertyInfo.SetValue(tmp_Class, 5, null); //给对应属性赋值
int value_New = (int)propertyInfo.GetValue(tmp_Class, null);
Console.WriteLine(value_New);
// Console.WriteLine();
Console.ReadLine();
}
}
另外附加点小知识:
1、GetType()方法继承自Object,所以C#中任何对象都具有GetType()方法,x.GetType(),其中x为变量名
2、typeof(x)中的x,必须是具体的类名、类型名称等,不可以是变量名称
3、System.Type.GetType(),有两个重载方法
比如有这样一个变量i:
Int32 i = new Int32();
使用GetType(),i.GetType()返回值是Int32的类型,但是无法使用typeof(i),因为i是一个变量,
使用typeof(),则只能:typeof(Int32),返回的同样是Int32的类型。