在我创建的许多其他类型中,可以使用downCast类型
我通常也创建一个扩展方法,因此它更容易管理…
BaseTypeM
BTDerV : BaseTypeM
BTDerLastDescndnt : BTDerV
现在我创建一个LastDerived类型并将其值分配给ParentType
BTDerV BTDer;
BTDerLastDescndnt BTDerLastDesc = new BTDerLastDescndnt(parA, ParB);
this.BTDer = BTDerLastDesc;
然后使用downCast扩展
var LDesc = this.BTDer.AsBTDerLastDescndnt();
这实际上是
public static BTDerLastDescndnt AsBTDerLastDescndnt(this BTDerV SelfBTDerV )
{
return (BTDerLastDescndnt)SelfBTDerV;
}
现在,当我这样做下面的代码,这里它编译,但给我一个运行时错误
//BTDerV---v v---BaseTypeM
public class SqlParDefV : SqlParameterM
{
public override SqlSpParDefMeta ParDMT
{
get {
return base.ParDMT;
}
set {
base.ParDMT = value;
}
}
public SqlParDefV(int bsprpOrdinal, string bsprpParName, MSSTypesS bdprpTypeS, bool bsprpIsDbStuctured, bool bsprpIsReq = true, ParameterDirection bsprpDirection = ParameterDirection.Input)
{
this.ParDMT = new SqlSpParDefMeta(bsprpOrdinal, bsprpParName, bdprpTypeS, bsprpIsReq, bsprpIsDbStuctured, bsprpDirection);
}
}
//BTDerLastDescndnt---v
public sealed class SqlParTvDrecDefinitionVScl : SqlParDefV
{
public override SqlSpParDefMeta ParDMT
{
get {
return base.ParDMT;
}
set {
base.ParDMT = value;
}
}
public SprocTvTargetSF.currentSDTObjType SqlObjType { get; set; }
public SqlMetaData[] Meta { get; set; }
public SqlParTvDrecDefinitionVScl(int bsprpOrdinal, string bsprpParName, SprocTvTargetSF.currentSDTObjType ctrSqlObjType, SqlMetaData[] parGeneratedSqlMetaData, MSSTypesS bdprpTypeS, bool bsprpIsDbStuctured, bool bsprpIsReq = true, ParameterDirection bsprpDirection = ParameterDirection.Input)
: base(bsprpOrdinal, bsprpParName, bdprpTypeS, bsprpIsDbStuctured, bsprpIsReq, bsprpDirection)
{
this.SqlObjType = ctrSqlObjType;
this.Meta = parGeneratedSqlMetaData;
}
}
这里有什么不寻常的事情,或者我迷茫并错过了一些基本规则?
最佳答案 我不确定从Derived到MoreDerived的演员在这里失败的确切原因.但是,潜在的解决方法(注意:可能代码味道)是as运算符:
public static MoreDerived AsMoreDerived (this Derived d)
{
return d as MoreDerived;
}
请注意,有效地尝试强制转换并返回null,因此您需要在那里进行适当的检查.