简体   繁体   中英

How to get Values from variable of type Object in c#

I have a variable of type Object which is typeof InquireSubscription

public class InquireSubscription: object, System.ComponentModel.INotifyPropertyChanged 
{
    public string planId {get; set}
}

I want to retrieve the planId value but i am totally stuck in finding out how to access the properties out of the Object item

Please have a look at the Screenshot:

在此处输入图片说明

EDITED eligibilityResult is of type SubscriptionEligibility

    public partial class SubscriptionEligibility: object, System.ComponentModel.INotifyPropertyChanged 
    {
         private object[] itemsField;

        [System.Xml.Serialization.XmlElementAttribute("InquireSubscription", typeof(SubscriptionEligibility), Order=0)]

        [System.Xml.Serialization.XmlElementAttribute("DeviceEligibilityResult", typeof(SubscriptionEligibility), Order=0)]

       public object[] Items {
           get {
             return this.itemsField;
           } 
           set {
              this.itemsField = value;
              this.RaisePropertyChanged("Items");
           }
        }

You can use LINQ:

foreach (var item in eligibilityResult.Items.OfType<InquireSubscription>())
{
    item.planId = ...;
}

This will ignore any Items that are not InquireSubscription or a subclass. Use Cast() if you want to be sure that it isn't the case:

foreach (var item in eligibilityResult.Items.Cast<InquireSubscription>())
{
    item.planId = ...;
}

If you own the code of SubscriptionEligibility you should instead try to refactor it to not use object if possible

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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