C#返回不同类型的? [英] C# Return Different Types?

查看:572
本文介绍了C#返回不同类型的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到了这样的事情:

public [What Here?] GetAnything()
{
     Hello hello = new Hello();
     Computer computer = new Computer();
     Radio radio = new Radio();

     return radio; or return computer; or return hello //should be possible?!      
}



我有一个方法,这方法返回值的我有时不同类型(类)。

I have a Method and this method returns me sometimes different Types of Values (classes).

我怎样才能做到这一点反正ofcourse后来与变量工作,b.e radio.Play();到目前为止?

How can I do this anyway and ofcourse later to work with the variables, b.e radio.Play(); and so far?

我需要使用泛型?怎么样?

Do I need to use generics? How?

推荐答案

如果没有公共基类或接口,那么公共对象GetAnything() {...} - 但它通常将是优选具有某种抽象诸如通用接口。例如,如果您好电脑无线所有实施的IFoo ,那么它可能会返回一个的IFoo

If there is no common base-type or interface, then public object GetAnything() {...} - but it would usually be preferable to have some kind of abstraction such as a common interface. For example if Hello, Computer and Radio all implemented IFoo, then it could return an IFoo.

这篇关于C#返回不同类型的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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