【问题标题】:get properties through a string object with c # - Xamarin forms使用 c# - Xamarin 表单通过字符串对象获取属性
【发布时间】:2017-03-01 17:06:33
【问题描述】:

我有一个包含 500 个属性的对象,我需要使用字符串动态调用该对象。如何使用 c#?

public class MyObjects
    {    
    public int RGP_Id { get; set; }
    public DateTime RGP_DateTime { get; set; }
    public int RGP_MCC_Numero_Serie_MS { get; set; }
    public int RGP_IDREG_1 { get; set; }
    public int RGP_IDREG_2 { get; set; }
    public int RGP_IDREG_3 { get; set; }
    public int RGP_IDREG_4 { get; set; }
    public int RGP_IDREG_5 { get; set; }
    public int RGP_IDREG_6 { get; set; }
    public int RGP_IDREG_7 { get; set; }
    public int RGP_IDREG_8 { get; set; }
    public int RGP_IDREG_9 { get; set; }
    public int RGP_IDREG_10 { get; set; }
    .......
    public int RGP_IDREG_500 { get; set; }

}

我需要调用对象的属性并使用字符串返回它的值。

目标示例:

var x = MyObjects.GetPropertyValue("RGP_IDREG_10"); 

有可能吗?

【问题讨论】:

  • 展示的目标对我来说并不是很清楚。你想要一个名为Equals()static 方法,它需要一个string,具体做什么?在这个操作之后x 会是什么?
  • 我需要通过字符串调用对象的属性并返回其值...
  • 这不是重复的@David,这是针对 xamarin 表单的....GetProperty() not exist in xamarin forms c#
  • 有趣。您能否详细说明您是如何尝试使用该解决方案的以及失败的原因?
  • 我正在尝试使用 GetType () 但没有可以通过字符串检索值的方法,反射我无法使用它,因为 .net xaamrin 表单不完全支持此功能。

标签: c# object reflection xamarin.forms equals


【解决方案1】:

您可以使用类似this question 的方式获取属性列表,然后访问该属性。您将需要使用 System.Reflection,但它应该可供您使用。

【讨论】:

    【解决方案2】:

    我建议使用除此之外的任何其他东西,因为它需要反射,并且反射可能会很慢,但如果你真的想这样做......

    using System.Reflection;
    
    ...
    
    var objects = new MyObjects();
    var propertyInfo = typeof(MyObjects).GetRuntimeProperty("RGP_IDREG_1");
    var value = (int)(propertyInfo.GetMethod.Invoke(objects, new object [] {}));
    

    【讨论】:

      【解决方案3】:

      Xamarin 表单中的解决方案

      var profile = MyObjects;
      var idProperty = GetProperty(profile.GetType().GetTypeInfo(), "RGP_IDREG_10");
      var x = idProperty.GetValue(profile, null);    
      

      idProperty 包含来自属性的值

      【讨论】:

      • 前提是GetProperty 做了我认为它做的事情,并且你要么混淆了调用扩展方法的方式,它不返回值,而是一个PropertyInfo
      • 对不起,我已经更正了,我忘了添加 GetValue。现在可以工作了。
      猜你喜欢
      • 1970-01-01
      • 2012-01-27
      • 1970-01-01
      • 2011-10-27
      • 2021-11-28
      • 2023-03-30
      • 2010-10-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多