c# - 将类型转换(向下转换)为另一个子类型时出现运行时错误

标签 c# casting type-conversion 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;
    }
}

这里有什么不寻常的地方吗?或者我是否感到困惑并错过了一些基本规则?

最佳答案

我不确定从 DerivedMoreDerived 的转换在这里失败的确切原因。但是,一个潜在的解决方法(注意:可能是代码味道)是 as 运算符:

public static MoreDerived AsMoreDerived (this Derived d)
{
    return d as MoreDerived;
}

请注意,as 有效地尝试转换并返回 null,因此您需要在那里进行适当的检查。

关于c# - 将类型转换(向下转换)为另一个子类型时出现运行时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34546753/

相关文章:

c# - Linq thenBy() 抛出 "The best overloaded method match ThenBy() for has some invalid arguments"异常

casting - SSIS 转换为 DT_WSTR 未转换,或者看起来是这样

c++ - 为什么我的 C++ 到十六进制转换会导致不同的格式?

c# - 编码UI : The Browser gets closed as finish testing without keeping for testing further steps

c# - 使用密码强度验证器和正则表达式时很少出现错误

java - 为什么我会收到此错误 "Type mismatch: cannot convert from Serializable to T"?

javascript - 如何将数值传递给 jQuery 的 .css()?

c++ - 如何将 int 转换为 char*?

c# - 如何在 Ocelot 中实现 cors header

java - 整数除法 : How do you produce a double?