gpt4 book ai didi

C# 如何在不知道您使用的是哪个 poco 的情况下将 Poco 转换为 List

转载 作者:太空宇宙 更新时间:2023-11-03 18:15:54 28 4
gpt4 key购买 nike

我有一个接受 的方法任意 POCO。然后,该方法需要能够检查 POCO 是否为 List<Poco>。 .如果不是列表,则需要将其转换为列表。

例子

MyCustomMethod(object input)
{
// if !input is list
// convert input to list
}

我会这样称呼它
MyCustomMethod(Pocos.foo);
MyCustomMethod(Pocos.bar);

记住 MyCustomMethod不知道什么 poco 被发送给它。它所知道的只是检查对象是否为列表,如果不是,则需要将其转换为同一对象的列表。

解决这个问题的最简单方法是什么?

编辑:

对此的一些推理可能会有所帮助。我正在构建一个 应用程序和 Ext.Data.Store要求所有 JSON 数据都在一个数组中。

我正在使用 构建我的 WebService我有一个自定义 JsonPResult . JsonPResult 接受任何对象并将该对象作为 JsonP 返回。如果我要向 JsonPResult 发送一个列表,那么一切都是肉汁。如果我只是发送一个对象,Sencha Touch 会呕吐,直到我将该对象放入一个数组中。

为了保持干燥,我希望 JsonPResult 检查是否有任何对象是一个列表,并完成工作,而不是在每个 Controller 中重复自己。

最佳答案

你可以做一个安全的 Actor :

var list = obj as List<Poco>;
if (list != null)
// It's a list and you now have a reference
else
list = new List<Poco> { (Poco)obj };

编辑 要支持任何 POCO,您需要使用泛型,所以这里有一个通用的扩展方法:
public static IList<T> AsList<T>(this T item)
{
var list = item as List<T>;
if (list != null)
return list;

return new List<T>() { item };
}

还有一些例子:
string name = "Matt";
var list = name.AsList();

List<string> names= new List<string>() { "Matt" };
var list2 = names.AsList();

两个 listlist2将是字符串列表,但在第二种情况下,它直接返回了转换列表,而不是创建一个新列表并将自己插入其中。类型推断负责泛型参数,它可以应用于任何类型。

关于C# 如何在不知道您使用的是哪个 poco 的情况下将 Poco 转换为 List<Poco>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6524077/

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