.NET反射的问题,可以算作.NET的bug吗?
在做项目的时候,定义类时一时疏忽,在子类中重复定义了父类的字段和属性,简化代码如下,实际情况由于子类和父类属性和字段比较多,通过反射从数据库中读取数据并给相应的类赋值的时候,经常出现莫名其妙的错误,明明是A类的Type,使用GetProperty("Type")时候出现异常后,居然得到了B类。程序里面变量的值也都改变了。调试了很长时间才怀疑错误出现在这上面。
心得:1、不要以为用了new关键字就万事大吉了,有时候这才是噩梦的开始。
2、反射并不是万能的,也有它处理不了的情况。
using System;
using System.Reflection;
class BaseClass
{
private byte m_bytType;
public byte Type
{
get
{
return m_bytType;
}
set
{
m_bytType = value;
}
}
}
class InheritClass : BaseClass
{
private int m_intType;
public new int Type
{
get
{
return m_intType;
}
set
{
m_intType = value;
}
}
}
class Test
{
static void Main()
{
InheritClass clsTest = new InheritClass();
clsTest.Type = 3;
Console.WriteLine(clsTest.Type);
Type classType = clsTest.GetType();
// 这个位置会抛出异常
PropertyInfo prtPropertyinfo = classType.GetProperty("Type");
prtPropertyinfo.SetValue(clsTest,3000,null);
Console.WriteLine(clsTest.Type);
}
}
using System.Reflection;
class BaseClass
{
private byte m_bytType;
public byte Type
{
get
{
return m_bytType;
}
set
{
m_bytType = value;
}
}
}
class InheritClass : BaseClass
{
private int m_intType;
public new int Type
{
get
{
return m_intType;
}
set
{
m_intType = value;
}
}
}
class Test
{
static void Main()
{
InheritClass clsTest = new InheritClass();
clsTest.Type = 3;
Console.WriteLine(clsTest.Type);
Type classType = clsTest.GetType();
// 这个位置会抛出异常
PropertyInfo prtPropertyinfo = classType.GetProperty("Type");
prtPropertyinfo.SetValue(clsTest,3000,null);
Console.WriteLine(clsTest.Type);
}
}