一种将基类型转换为派生类型的方法 [英] A way of casting a base type to a derived type

查看:30
本文介绍了一种将基类型转换为派生类型的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定这是否是一件奇怪的事情,或者它是否是代码的味道......但我想知道是否有一种方法(某种oop模式会很好)将基类型强制转换"为其派生类型的一种形式.我知道这没有什么意义,因为派生类型将具有父级不提供的附加功能,而这些功能本身从根本上来说并不健全.但是有没有办法做到这一点?这是一个代码示例,以便我可以更好地解释我的要求.

I'm not sure if this is a strange thing to do or not, or if it is some how code smell...but I was wondering if there was a way (some sort of oop pattern would be nice) to "cast" a base type to a form of its derived type. I know this makes little sense as the derived type will have additional functionality that the parent doesn't offer which is in its self not fundamentally sound. But is there some way to do this? Here is a code example to so I can better explain what I"m asking.

public class SomeBaseClass {
    public string GetBaseClassName {get;set;}
    public bool BooleanEvaluator {get;set;}
}

public class SomeDerivedClass : SomeBaseClass {
    public void Insert(SqlConnection connection) {
          //...random connection stuff
          cmd.Parameters["IsItTrue"].Value = this.BooleanEvalutar;
          //...
    }
}

public static void Main(object[] args) {
    SomeBaseClass baseClass = new SomeBaseClass();
    SomeDerivedClass derClass = (SomeDerivedClass)baseClass; 
    derClass.Insert(new sqlConnection());
}

我知道这看起来很愚蠢,但有没有办法完成这种事情?

I know this seems goofy but is there any way to accomplish something of this sort?

推荐答案

不太好,在托管"语言中.这是向下转型,并且没有理智的方法来处理它,这正是您描述的原因(子类提供的不仅仅是基类 - 这个更多"来自哪里?).如果您真的希望特定层次结构具有类似的行为,您可以为派生类型使用构造函数,将基类型作为原型.

Not soundly, in "managed" languages. This is downcasting, and there is no sane down way to handle it, for exactly the reason you described (subclasses provide more than base classes - where does this "more" come from?). If you really want a similar behaviour for a particular hierarchy, you could use constructors for derived types that will take the base type as a prototype.

可以用反射构建一些处理简单情况的东西(更具体的类型,没有附加状态).一般来说,只需重新设计即可避免问题.

One could build something with reflection that handled the simple cases (more specific types that have no addition state). In general, just redesign to avoid the problem.

糟糕,不能在基/派生类型之间编写转换运算符.微软试图保护你"对抗你自己的奇怪之处.嗯,至少他们不像 Sun 那样糟糕.

Woops, can't write conversion operators between base/derived types. An oddity of Microsoft trying to "protect you" against yourself. Ah well, at least they're no where near as bad as Sun.

这篇关于一种将基类型转换为派生类型的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆