写了两个类
public class BaseA
{
....}
public class A:BaseA
{...}但当我写以下调用时却报错:如果想强制转换该处理是好?
BaseA baseA=某类.get();
A a=(A)baseA
转换时提示,不允许强制转换,这该如何是好?
public class BaseA
{
....}
public class A:BaseA
{...}但当我写以下调用时却报错:如果想强制转换该处理是好?
BaseA baseA=某类.get();
A a=(A)baseA
转换时提示,不允许强制转换,这该如何是好?
if (a!=null)
{
}
父类对像在new出来的时候是父类对像
只能是父类对像
如果你是先new的一个子类,然后用一个父类型变量引用了它,然后再用另一个同样的子类变量引用父类型变量的强制转换是可以的.
即:
A a = new A();
BaseA ba = a;
A b = (A)ba;
是可以的
可以自由转换两个实体对象:以供参考public static void AsObject(object fromObj, object toObj)
{
string name = "";
object attValue=null;
Type fromType=fromObj.GetType();
Type toType=toObj.GetType();
PropertyInfo[] attributes = fromType.GetProperties();
PropertyInfo[] toAttributes=toType.GetProperties();
for (int i = 0; i < attributes.Length; i++)
{
name = attributes[i].Name;
if (attributes[i].CanRead)
{
attValue = attributes[i].GetValue(fromObj, BindingFlags.GetProperty, null, null, null);
for(int j=0;j<toAttributes.Length;j++)
{
if(name!=toAttributes[j].Name)continue;
if (toAttributes[j].CanWrite) toAttributes[j].SetValue(toObj, attValue, BindingFlags.SetProperty, null, null, null);
break;
}
}
}
}