简体   繁体   English

C# 如何将 Poco 转换为 List<poco> 不知道你使用的是哪个 poco</poco>

[英]C# How to convert Poco to List<Poco> without knowing which poco you're using

I've got a method that accepts any POCO.我有一个接受任何POCO 的方法。 The method then needs to be able to check to see if the POCO is a List<Poco> .然后,该方法需要能够检查 POCO 是否为List<Poco> If it's not a list, it needs to convert it to a list.如果不是列表,则需要将其转换为列表。

Example例子

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

And I would call it as such我会这样称呼它

MyCustomMethod(Pocos.foo);
MyCustomMethod(Pocos.bar);

Remember MyCustomMethod has no idea what poco is being sent to it.请记住, MyCustomMethod不知道发送给它的 poco 是什么。 All it knows is to check if the object is a list, and if it's not, it needs to convert it to a list of that same object.它所知道的只是检查 object 是否是一个列表,如果不是,它需要将其转换为同一个 object 的列表。

What would be the easiest way to approach this?解决这个问题的最简单方法是什么?

EDIT:编辑:

Some reasoning for this might help.对此的一些推理可能会有所帮助。 I'm building a app, and the Ext.Data.Store requires all JSON data to be in an array.我正在构建一个 sencha 应用程序, Ext.Data.Store要求所有 JSON 数据都在一个数组中。

I'm building my WebService using and I've got a custom JsonPResult .我正在使用构建我的 WebService,并且我有一个自定义的JsonPResult The JsonPResult accepts any object and returns that object as JsonP. JsonPResult 接受任何 object 并将 object 作为 JsonP 返回。 If I'm sending a list to the JsonPResult, everything is gravy.如果我要向 JsonPResult 发送一个列表,那么一切都是肉汁。 If I'm just sending a single object, Sencha Touch pukes until I put that object into an array.如果我只是发送一个 object,Sencha Touch 会呕吐,直到我将 object 放入一个数组中。

In order to keep things DRY, I'd like the JsonPResult to check if any object is a list, and do the work, rather than repeating myself in every controller.为了保持干燥,我希望 JsonPResult 检查是否有任何 object 是一个列表,并完成工作,而不是在每个 controller 中重复自己。

You could do a safe cast:你可以做一个安全的演员:

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 };

Edit to support any POCO, you'll need to use generics, so here is a generic extension method for you:编辑以支持任何 POCO,您需要使用 generics,所以这是一个通用的扩展方法:

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 };
}

And some examples:还有一些例子:

string name = "Matt";
var list = name.AsList();

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

Both list and list2 will be lists of strings, but in the second instance, it has returned the casted list directly, instead of creating a new one and inserting itself into it. listlist2都是字符串列表,但在第二种情况下,它直接返回了转换后的列表,而不是创建一个新列表并将其自身插入其中。 Type inference takes care of the generic argument, and it can be applied to any type.类型推断负责泛型参数,它可以应用于任何类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM