c# - 如何返回多种数据类型

标签 c# .net return-type

我有一个方法,我希望能够返回一个 IWebElements 列表,一个仅包含元素名称的列表或一个字符串数组。是否可以用一种方法返回多种数据类型?有没有更可行的方法来获得不同的返回类型而无需仅使用一种方法?

/// <summary>
/// Gets all options belonging to this selected tag
/// </summary>
/// <returns>Returns a list of IWebElements</returns>
public List<IWebElement> SelectAllOptions(IWebDriver driver, ref DataObject masterData)
{
    //Get the ID of the dropdown menu
    DatabaseRetrieval.GetObjectRepository(ref masterData);
    var strDropMenuId = masterData.DictObjectRepository["ID"];
    //Find the dropdown menu and pull all options into a list
    try
    {
        var dropMenu = new SelectElement(driver.FindElement(By.Id(strDropMenuId)));
        return dropMenu.Options as List<IWebElement>;
    }
    catch (NoSuchElementException exception)
    {
        masterData.Logger.Log(Loglevel.Error, "Boom: {0}", exception.Message);
    }
    masterData.Logger.Log(Loglevel.Debug, "No options found for DropDownMenu: {0}", strDropMenuId);
    return null;
}

最佳答案

您不能返回多种类型。但是,您可以:

  1. 创建一个包含所有可能返回类型的类型
  2. 使用 .Net 的 Tuple相反
  3. 有参数。

但这是一个非常糟糕的设计决定,您真的应该考虑避免它。 (这通常意味着你的方法做的比它应该做的多)

关于c# - 如何返回多种数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23346126/

相关文章:

c# - Identityserver3 - 一个 id 服务器颁发的访问 token 是否可以与另一 id 服务器一起使用?

c# - 隐藏 Windows 8 桌面图标

c# - 'GridView1'的DataSourceID必须是IDataSource类型控件的ID

c - 函数没有返回类型?

C++返回类型指针声明

c# - 自定义自动生成的部分类

c# - 最小起订量 功能参数

c# - NHibernate 映射 : Save hierarchy to single table without discriminator

c# - 尝试写入空十进制值时出现 Filehelpers NullReferenceException

c - 有没有办法保持函数变量的返回类型?