简体   繁体   English

将 Object 转换为通用列表

[英]Cast Object to Generic List

I have 3 generict type list.我有 3 个泛型类型列表。

List<Contact> = new List<Contact>();
List<Address> = new List<Address>();
List<Document> = new List<Document>();

And save it on a variable with type object.并将其保存在类型为 object 的变量中。 Now i nedd do Cast Back to List to perfom a foreach, some like this:现在我需要做 Cast Back to List 来执行 foreach,有些像这样:

List<Contact> = (List<Contact>)obj;

But obj content change every time, and i have some like this:但是 obj 内容每次都在变化,我有一些这样的:

List<???> = (List<???>)obj;

I have another variable holding current obj Type:我有另一个持有当前 obj 类型的变量:

Type t = typeof(obj);

Can i do some thing like that??:我可以做这样的事情吗??:

List<t> = (List<t>)obj;

Obs: I no the current type in the list but i need to cast, and i dont now another form instead: Obs:我没有列表中的当前类型,但我需要转换,我现在不需要另一种形式:

List<Contact> = new List<Contact>();

What a sticky problem. 多么棘手的问题。 Try this: 尝试这个:

List<Contact> c = null;
List<Address> a = null;
List<Document> d = null;

object o = GetObject();

c = o as List<Contact>;
a = o as List<Address>;
d = o as List<Document>;

Between c, a, and d, there's 2 nulls and 1 non-null, or 3 nulls. 在c,a和d之间,有2个空值和1个非空值或3个空值。


Take 2: 采取2:

object o = GetObject();
IEnumerable e = o as IEnumerable;
IEnumerable<Contact> c = e.OfType<Contact>();
IEnumerable<Address> a = e.OfType<Address>();
IEnumerable<Document> d = e.OfType<Document>();

Lots of trial and error gave me this on SL 5 but it should also work on a regular C#. 许多尝试和错误使我在SL 5上获得了此功能,但它也应在常规C#上运行。 You also need to add LINQ to your using list for the last half to work. 您还需要将LINQ添加到使用列表中,才能使后半部分正常工作。

    List<object> myAnythingList = (value as IEnumerable<object>).Cast<object>().ToList()

Enjoy! 请享用!

I had the same problem and solved it by looking at the purpose of the casted objects. 我遇到了同样的问题,并通过查看投射对象的目的来解决了这个问题。 Do you really need to cast it to the specific (closed) generic types? 您是否真的需要将其转换为特定的(封闭的)泛型类型? In my case the (open) generic type had an interface which I used to cast it to. 在我的情况下,(开放)泛型类型具有用于将其强制转换为的接口。

var list = obj as IUsefulInterface;

list.MethodThatIAmInterestedIn();

A general solution like this (to instantiate a type with a generic parameter based on a System.Type object) is not possible. 这样的通用解决方案(以基于System.Type对象的通用参数实例化类型)是不可能的。 If you're really just dealing with these three types, though, then you're in luck because it's pretty easy: 但是,如果您真的只是在处理这三种类型,那么您很幸运,因为它很简单:

Type t = typeof(obj);

if (t == typeof(List<Contact>)) {
    var contactList = (List<Contact>)obj;
    // do stuff with contactList

} else if (t == typeof(List<Address>)) {
    var addressList = (List<Address>)obj;
    // do stuff with addressList

} else if (t == typeof(List<Document>)) {
    var documentList = (List<Document>)obj;
    // do stuff with documentList
}

I had this problem when writing a Validation Attribute where I received an object from the ValidationContext and knew that it needed to be a list, but not what it was a list of. 我在编写Validation Attribute时遇到了这个问题,我从ValidationContext接收到一个对象,并且知道它需要是一个列表,而不是它的列表。 It threw an exception when I tried to cast it as IEnumerable<object> but it could be cast as IEnumerable which then allowed the .Cast<object>() via linq. 当我尝试将其.Cast<object>()IEnumerable<object>时,它引发了一个异常,但可以将其.Cast<object>()IEnumerable ,从而允许通过linq的.Cast<object>()

In the end what worked was: 最后有效的是:

var enumerable = listObject as IEnumerable;
var list = enumerable.Cast<object>().ToList();

No, you can't cast without going around corners (this is: reflection), generic type parameters have to be known at compile time. 不,您不能不进行强制转换(这是反射),必须在编译时知道泛型类型参数。 You can of course do something like this: 您当然可以这样做:

content.Where(o => o is type).ToList().Foreach(stuff);

I ran into same problem - I have a collection which data type is only known at run time and I can't cast it to anything. 我遇到了同样的问题-我有一个集合,该集合的数据类型仅在运行时才知道,我无法将其转换为任何东西。 None of the solutions above worked. 上述解决方案均无效。 Finally I solved it by serializing to JSON and de-serializing back. 最后,我通过序列化为JSON并反序列化来解决它。 Of course it's not ideal, but may help someone. 当然这不是理想的,但是可以帮助某人。

string jsonString = JsonConvert.SerializeObject(myObject);
jsonString = "{ values:" + jsonString + "}";

JObject j = JObject.Parse(jsonString);

//now we can iterate over the list
foreach (var x in j["values"])
{
    string name = x.ToString();
    ...
}
Employee employee=new Employee();
List<Employee> emplist=new();
emplist.Add(employee);

This is correct way Thank you这是正确的方法谢谢

You might need to do: 您可能需要做:

if(object is List)
{
    list = (List)object
}

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

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