Rob*_*cks 4 c# types base-class strong-typing
我经常使用以下方法将对象链接到父母:
Video parent;
Run Code Online (Sandbox Code Playgroud)
有时我的对象可以是不同对象类型的子对象,所以我:
int parentType;
Video parentVideo; // if parent == VIDEO then this will be used
Audio parentAudio; // if parent == AUDIO then this will be used
Run Code Online (Sandbox Code Playgroud)
有没有更好的办法?如何使用可以是不同类型实例的变量?
编辑:当然,如果视频和音频继承自相同的基类(例如媒体),我可以这样做:
Media parent;
Run Code Online (Sandbox Code Playgroud)
但是,如果父母不继承同一个基类怎么办?
小智 9
我假设您的问题中的类型是密封的.在这种情况下,我会在出路时使用object parent
和使用as
.(使用as
可以比检查标志具有更高的性能影响,但是...在我做过的任何事情中都不是问题,它也可以很好地用在空值保护中.)
Video video = null;
if ((video = parent as Video) != null) {
// know we have a (non-null) Video object here, yay!
} else if (...) {
// maybe there is the Audio here
}
Run Code Online (Sandbox Code Playgroud)
以上实际上只是一种愚蠢的C#方式,在一个不受约束的歧视联盟上编写一次性模式匹配(对象是C#中所有其他类型的联合:-)
好吧,通常一个暴露所有功能的界面是合适的,这可以是你的类型.否则(或同样)你可以考虑泛型:
像这样:
class Something<TMediaType>
where TMediaType : IMedia // use this statement to limit the types. It
// is not required, if not specified it can be
// of any type
{
TMediaType data;
// other such things
}
Run Code Online (Sandbox Code Playgroud)