문제

I have a method parameter of type Object response. I'm iterating through the object using:

foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(response))
{
    string name = descriptor.Name;
    object value = descriptor.GetValue(response);

    Console.WriteLine("{0}={1}", name, value);

    if (name.Contains("StatusData"))
    {
        //loop thorugh StatusDataReponse properties
    }

When the object contains a property of StatusData, I need to convert it to StatusDataResponse and loop through it's properties. I'm coming from vb.net and not sure how to do this in c#.

도움이 되었습니까?

해결책 3

To be really straightforward:

    foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(response))
    {
        string name = descriptor.Name;
        object value = descriptor.GetValue(response);

        Console.WriteLine("{0}={1}", name, value);

        if (name.Contains("StatusData"))
        {
            foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(value))
            {
               ...
            }
        }
    }

다른 팁

Since you know the type, you can convert the value directly:

if (name.Contains("StatusData"))
{
    //loop thorugh StatusDataReponse properties
    StatusDataReponse response = value as StatusDataReponse;
    if (response != null)
    {
       // Use response as needed
    }
}

you read about covariance and contravariance in c# .Try to use this.I think it will work if value is inherited property.If I am wrong please comment.

 if (name.Contains("StatusData"))
    {
        //loop thorugh StatusDataReponse properties
        StatusDataReponse response = (StatusDataReponse)value;
        if (response != null)
        {
           // Use response as needed
        }
    }

If I were you, I would not check on the name, but just check on the type. This way you are safe for:

  1. All properties with another name than StatusData but which is of type StatusDataReponse.
  2. All properties with the name StatusData but which are NOT of type StatusDataReponse.

Exaple:

foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(response))
{
    string name = descriptor.Name;
    object value = descriptor.GetValue(response);
    StatusDataReponse statusData = value as StatusDataReponse; 

    if (statusData == null)
    {
        Console.WriteLine("{0}={1}", name, value);
    }
    else
    {
        //loop thorugh StatusDataReponse properties
    }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top