【问题标题】:How to use reflection to show properties of Web Service with a List<CustomClass>如何使用反射通过 List<CustomClass> 显示 Web 服务的属性
【发布时间】:2015-03-28 01:57:50
【问题描述】:

我在this question 上成功实现了答案。但是,当我有一个列表时它不起作用。当我运行这个时,这就是我得到的结果:

AccountDataResult: 'AccountFound'
AccountList: 'CustomWebService.TestApplication.ServiceMethods.CustomClassOutputData+DataList[]'

这个列表里面有 X 个项目,我需要列出每个项目的所有属性。实现这一目标的最佳方法是什么?

这是我今天拥有的:

void AddPropertiesToTextbox(object output, TextBox txt)
{
   PropertyInfo[] piData = null;
   piData = Utility.GetPublicProperties(output.GetType());

   foreach (PropertyInfo pi in piData)
   {
      if (pi.Name.ToLower() != "extensiondata")
      {
         textResult.Text += string.Format("{0}: '{1}'", pi.Name, pi.GetValue(output, null));
         textResult.Text += Environment.NewLine;
      }
   }
}

这是我的网络服务模型:

[DataContract]
public class OutputData
{
    [DataContract]
    public class AccountData
    {
        [DataMember]
        public string AccountStatus { get; set; }

        [DataMember]
        public string FirstName { get; set; }

        [DataMember]
        public string LastName { get; set; }

    }

    [DataContract]
    public enum AccountDataResults
    {
        [EnumMember]
        None,
        [EnumMember]
        AccountFound,
        [EnumMember]
        NoAccounts
    }

    [DataMember]
    public List<AccountData> DataList { get; set; }

    [DataMember]
    public AccountDataResults AccountDataResult { get; set; }
}

【问题讨论】:

    标签: c# list webservice-client system.reflection


    【解决方案1】:

    你可以通过调用GetGenericTypeDefinition()来检查PropertyInfo'sPropertyType类型定义

    if(pi.PropertyType.GetGenericTypeDefinition() == typeof(List<>))
    {
       // recurse through properties
    }
    

    【讨论】:

      【解决方案2】:

      演示:

      class Program
      {
          static void Main(string[] args)
          {
              object test = new Test { DemoProperty = "Some", DemoListProperty = new List<int> { 1, 2, 3, 4 } };
      
              Type type = typeof(Test);
              foreach (var pi in type.GetProperties())
              {
                  if (pi.PropertyType.IsGenericType && pi.PropertyType.GetGenericTypeDefinition() == typeof(List<>))
                  {
                      IEnumerable objects = pi.GetGetMethod().Invoke(test,null) as IEnumerable;
                      foreach (var o in objects)
                      {
                          Console.WriteLine(o); //may want to do recursion here and iterate over these properties too
                      }
                  }
              }
          }
      }
      
      class Test
      {
          public string DemoProperty { get; set; }
          public List<int> DemoListProperty { get; set; }
      }
      

      【讨论】:

      • 这在处理来自 Web 服务的类时似乎不起作用。我将您的代码复制/粘贴到我的程序中并运行它,它似乎可以工作,但是当我更改时: Type type = typeof(MyOutputClass);它不再提取任何属性。
      • 它只是一个演示......使用您现有的代码获取信息并使用它 if block
      • @KyleCrabtree 您是否尝试在 if 块中放置断点?是否进入区块?
      • 我用我的模型更新了原始问题,这可能有助于理解。从 Web 服务更改为我的类后,pi.PropertyType.IsGenericType = false,这就是它从不返回任何数据的原因。
      • @KyleCrabtree 那么当你到达 List 属性时你得到的是什么类型的?
      【解决方案3】:

      为了让这个工作,我不得不放弃我的初始设置。这就是我现在正在做的事情。这对我来说非常有效!这用于将 我关心的所有属性拉到结果列表中。

      获取任何类型的所有属性:

      public static PropertyInfo[] GetPublicProperties2(this Type type)
      {
          return type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
      }
      

      然后我有了这个方法,该方法对于任何在存在数组时调用自身的属性都是通用的。

      void AddPropertiesToTextbox(object output, string rootNamespace = "")
          {
              PropertyInfo[] piData = null;
              piData = Utility.GetPublicProperties2(output.GetType());
      
              foreach (PropertyInfo pi in piData)
              {
                  if (pi.PropertyType.IsArray == true)
                  {
                      Array subOutput = (Array)pi.GetValue(output);
      
      
                      for (int i = 0; i < subOutput.Length; i++)
                      {
                          textResult.Text += string.Format("{0}------------------------{0}", Environment.NewLine);
                          object o = subOutput.GetValue(i);
                          AddPropertiesToTextbox(o, pi.Name);
                      }
                  }
                  else
                  {
                      if (pi.Name.ToLower() != "extensiondata")
                      {
                          if (string.IsNullOrWhiteSpace(rootNamespace) == false) {
                              textResult.Text += string.Format("{2}.{0}: '{1}'", pi.Name, pi.GetValue(output, null), rootNamespace);
                          textResult.Text += Environment.NewLine;
                          } else {
                              textResult.Text += string.Format("{0}: '{1}'", pi.Name, pi.GetValue(output, null));
                          textResult.Text += Environment.NewLine;
                          }
      
                      }
                  }
              }
          }
      

      【讨论】:

        猜你喜欢
        • 2010-11-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-02
        • 1970-01-01
        • 1970-01-01
        • 2020-11-16
        • 2023-03-31
        相关资源
        最近更新 更多