如何使用可以是多种类型的变量?
我经常使用以下方法将对象链接到其父对象:
Video parent;
有时我的对象可以是不同对象类型的子对象,我也是这样:
int parentType;
Video parentVideo; // if parent == VIDEO then this will be used
Audio parentAudio; // if parent == AUDIO then this will be used
有更好的方法吗? 如何使用可以是不同类型实例的变量?
编辑:当然,如果视频和音频继承自同一个基类(例如媒体),我可以这样做:
Media parent;
但是如果父级不继承自同一个基类怎么办?
I frequently link objects to their parents using:
Video parent;
Sometimes I have objects that can be children of different object types, so do I:
int parentType;
Video parentVideo; // if parent == VIDEO then this will be used
Audio parentAudio; // if parent == AUDIO then this will be used
Is there a better way?
How do I work with a variable that can be an instance of different types?
Edit: Of course, if Video and Audio inherit from the same baseclass (eg. Media) I could do this:
Media parent;
But what if the parents do not inherit from the same baseclass?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我假设您问题中的类型是密封的。在这种情况下,我只会使用
objectparent
并在退出时使用as
。 (使用as
比检查标志具有更高的性能影响,但是......我所做的任何事情都不是问题,它也可以很好地用在 null-guard 中。)上面是实际上只是一种愚蠢的 C# 方式,在无约束的可区分联合上编写一次性模式匹配(对象是 C# 中所有其他类型的联合:-)
I am assuming that the types in your question are sealed. In which case I would just use
object parent
and useas
on the way out. (Usingas
can have a higher performance impact than checking a flag, but... not a concern in anything I have done and it can also be nicely used in a null-guard.)The above is actually just a silly C# way of writing a one-off-pattern-match on an unconstrained discriminated union (object is the union of every other type in C# :-)
好吧,通常公开所有功能的接口是合适的,这可以是您的类型。否则(或同时)你可以考虑泛型:
像这样:
Well, generally an interface which exposes all functionality is appropriate, and this can be your type. Otherwise (or as well as) you may consider generics:
Like so:
尝试扭转局面......这更有意义吗?
Try turning things around....does this make more sense ?
如果没有派生它们的基类 Media,但存在可以同样适用于音频或视频内容的通用功能,那么您可以创建一个新的 MediaContainer 类,该类接受对象内容并根据特定内容执行不同的操作内容类型。这样做的作用是将丑陋的“切换”功能封装到包装器中,以便您可以编写依赖于 MediaContainer 的代码,而不必担心它包含的特定 Media 或它如何处理委托调用的丑陋工作。
If there is not a base class Media from which they derive, but there is common functionality that could apply equally well to Audio or Video content, then you could create a new MediaContainer class that accepts an Object Content and performs operations differently depending on the specific type of Content. What this does is encapsulate the ugly 'switching' functionality into a wrapper so that you can write code that depends on a MediaContainer without worrying about the specific Media it contains or how it handles the ugly work of delegating the calls.