c# - 返回 T 其中有不同的返回类型

标签 c# syndication syndication-feed syndication-item

我有不同的返回类型,所以我无法决定使用什么。 我在考虑类似下面的内容,但如果您有其他想法,我愿意接受。

public T GetValue<T>(ContentType type)
{
    foreach (SyndicationItem item in feed.Items)
    {
        switch (type)
        {
            case ContentType.BaseUri:
                return item.BaseUri;
                break;
            case ContentType.Categories:
                return item.Categories;
                break;
            case ContentType.Content:
                return item.Content;
                break;
            case ContentType.Contributors:
                return item.Contributors;
                break;
            case ContentType.Copyright:
                return item.Copyright;
                break;
          }
     }
}

public enum ContentType
{
    BaseUri,
    Categories,
    Content,
    Contributors,
    Copyright
}

我想决定我要返回什么类型以便它匹配,否则它会抛出一个编译时错误。

最佳答案

我不明白将 switch case 放在 for 循环中的意义。你将在你的 switch 的一个 case 第一次为真时退出循环。
但是为了处理返回类型的不确定性问题,如果你知道返回类型是引用类型,那么你也可以这样做:

您可以将返回类型设置为object,然后调用者必须进行转换:

public object GetValue(ContentType type)
{
    switch (type)
    {
        case ContentType.BaseUri:
            return item.BaseUri;
            break;
        case ContentType.Categories:
            return item.Categories;
            break;
        case ContentType.Content:
            return item.Content;
            break;
        case ContentType.Contributors:
            return item.Contributors;
            break;
        case ContentType.Copyright:
            return item.Copyright;
            break;
      }
}

来电者:

public void Caller() 
{
    object x = GetValue();
    if ( x.GetType() == typeof(BaseUri) ) // I assume that BaseUri is also a class name
    {
        BaseUri baseUri = (BaseUri)x;
        // now you can use baseUri to initialize another variable in outer scopes ... or use it as a parameter to some method or ...
    }
    else if(x.GetType() == typeof(Category))
    {
        // the same logic of casting and using goes here too ...
    }
}

关于c# - 返回 T 其中有不同的返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55587150/

相关文章:

c# - 从网页预填充网页

c# - 通过带有前缀的 yaml 从 keyvault 动态获取多个 secret

c# - 构建一个简单的 RSS 阅读器,检索内容

c# - Asp.net 核心中的 SyndicationFeed

c# - SyndicationItem.Content 为空

c# - 不确定 linq to sql 查询的返回类型

c# - C#中小数据类型是如何打包的

rss - 使用 RSS 2.0 中的类别标签链接到完整的类别页面

php - 如何使用 PHP 在另一个站点中显示一个站点的内容?

c# - 聚合 RSS 阅读器因 XML 无效而失败?