开发者

Casting a C# List<>

开发者 https://www.devze.com 2023-02-16 23:31 出处:网络
I have what seems to be a simple problem but one that I can\'t seem to find answers to. I have a class with properties. One of those properties returns a List. I have a method that cycles through all

I have what seems to be a simple problem but one that I can't seem to find answers to. I have a class with properties. One of those properties returns a List. I have a method that cycles through all properties of any kind of class and produces a TreeNode for that class (a communication log application). When I come across the property identified as a List, I don't know how to cast the property.GetValue properly. the property.PropertyType is known but开发者_开发知识库 what ever I try, I get a compilation error or a runtime error.

Here is what I'm trying to do...

foreach (PropertyInfo prop in props)
{
    if(prop.PropertyType.Namespace == "System.Collections.Generic")
    {
        List<object> oList = prop.GetValue(data, null);
        MessageBox.Show(oList.Count.ToString())
    }
}

If I put a breakpoint on the GetValue line, the prop parameter knows that it's a list of "myclass" items with three elements. I just can't cast it to either a list of objects (which would be fine) or cast it to a list of actual "myclass" elements which would be even better. How do I cast the return value of PropertyInfo.GetValue (an object) to its List?


First of all, it's not enough (or needed in this case at all) to check the namespace. You can check if prop.PropertyType is an instance of ICollection (you can use IsAssignableFrom). I'm suggesting ICollection because you only seem to care about the Count.

You can then cast it to an ICollection (non-generic) and run Enumerable.Cast, like:

IEnumerable<MyClass> res = ((ICollection)prop.GetValue(data,null)).Cast<MyClass>();
MessageBox.Show(res.Count().ToString());

The advantage over converting directly to List is that this will work with any collection. But if you don't need that, you can try what the other answer suggests.


did you try

prop.GetValue(data, null) as List<YourClass>;


I guess you want contravariance.

Are you trying to do so?

List<object> list = (List<Product>)object;

List<object> and List<Product> wouldn't be treated as the same type.

C# 4.0 introduced covariance and contravariance for interface and delegate generic parameters, but anyway, IList<T> doesn't have contravariance.

In my humild opinion, I believe you'll need to reconsider your object graph!

PD: Just comment out if you want guidance for that!

0

精彩评论

暂无评论...
验证码 换一张
取 消