gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 16:58:44 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com