【问题标题】:Get value of a specific object property in C# without knowing the class behind在不知道后面的类的情况下获取 C# 中特定对象属性的值
【发布时间】:2012-07-09 12:46:55
【问题描述】:

我有一个“object”类型的对象 (.NET)。在运行时我不知道它背后的“真实类型(类)”,但我知道,该对象有一个属性“string name”。如何检索“名称”的值?这可能吗?

类似这样的:

object item = AnyFunction(....);
string value = item.name;

【问题讨论】:

  • GetValue(item, "PropertyName")
  • 可以使用System.Reflection获取对象类型,然后新建该类型的变量,使其等于item,然后访问属性-switchonthecode.com/tutorials/…
  • 你控制AnyFunction吗?为什么不在这里使用接口?并让 AnyFunction 返回 IHasName 或其他内容。

标签: c# .net


【解决方案1】:

您可以使用dynamic 而不是object

dynamic item = AnyFunction(....);
string value = item.name;

请注意,Dynamic Language Runtime (DLR) 具有内置缓存机制,因此后续调用非常快。

【讨论】:

  • 能否给一个“动态”的链接。谢谢。
【解决方案2】:

使用反射

System.Reflection.PropertyInfo pi = item.GetType().GetProperty("name");
String name = (String)(pi.GetValue(item, null));

【讨论】:

    【解决方案3】:

    反思可以帮助你。

    var someObject;
    var propertyName = "PropertyWhichValueYouWantToKnow";
    var propertyName = someObject.GetType().GetProperty(propertyName).GetValue(someObject, null);
    

    【讨论】:

      【解决方案4】:

      您可以使用动态而不是对象来做到这一点:

      dynamic item = AnyFunction(....);
      string value = item["name"].Value;
      

      【讨论】:

        【解决方案5】:

        反射和动态值访问是这个问题的正确解决方案,但速度很慢。 如果您想要更快的东西,那么您可以使用表达式创建动态方法:

          object value = GetValue();
          string propertyName = "MyProperty";
        
          var parameter = Expression.Parameter(typeof(object));
          var cast = Expression.Convert(parameter, value.GetType());
          var propertyGetter = Expression.Property(cast, propertyName);
          var castResult = Expression.Convert(propertyGetter, typeof(object));//for boxing
        
          var propertyRetriver = Expression.Lambda<Func<object, object>>(castResult, parameter).Compile();
        
         var retrivedPropertyValue = propertyRetriver(value);
        

        如果您缓存创建的函数,这种方式会更快。例如,在字典中,假设属性名称未更改或类型和属性名称的某种组合,则 key 将是对象的实际类型。

        【讨论】:

          【解决方案6】:

          在某些情况下,反射无法正常工作。

          如果所有项目类型都相同,您可以使用字典。 例如,如果您的项目是字符串:

          Dictionary<string, string> response = JsonConvert.DeserializeObject<Dictionary<string, string>>(item);
          

          或整数:

          Dictionary<string, int> response = JsonConvert.DeserializeObject<Dictionary<string, int>>(item);
          

          【讨论】:

            【解决方案7】:

            只需对对象的所有属性尝试此操作,

            foreach (var prop in myobject.GetType().GetProperties(BindingFlags.Public|BindingFlags.Instance))
            {
               var propertyName = prop.Name;
               var propertyValue = myobject.GetType().GetProperty(propertyName).GetValue(myobject, null);
            
               //Debug.Print(prop.Name);
               //Debug.Print(Functions.convertNullableToString(propertyValue));
            
               Debug.Print(string.Format("Property Name={0} , Value={1}", prop.Name, Functions.convertNullableToString(propertyValue)));
            }
            

            注意:Functions.convertNullableToString() 是自定义函数,用于将 NULL 值转换为 string.empty。

            【讨论】:

              猜你喜欢
              • 2023-03-17
              • 1970-01-01
              • 2012-10-16
              • 1970-01-01
              • 1970-01-01
              • 2013-05-10
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多