【问题标题】:Call the object inside the class using the user input使用用户输入调用类内的对象
【发布时间】:2019-09-16 20:31:22
【问题描述】:

我想编写一个简单的代码来获取用户输入并从一个类中获取它。由于类中的大量对象我不想使用 if 或 switch,告诉我我该怎么做就像下面的代码或向我建议一个简单的代码,当我使用这个代码时它告诉我标识符预期

public class Rates
{
    public double IRR { get; set; }
    public double ISK { get; set; }
    public double JEP { get; set; }
    public double JMD { get; set; }//my object are more
    public double JOD { get; set; }
    public double JPY { get; set; }
    public double KES { get; set; }
    public double KGS { get; set; }
    public double ZWL { get; set; }
}
public class RootObject_1
{
    public string disclaimer { get; set; }
    public string license { get; set; }
    public int timestamp { get; set; }
    public string @base { get; set; }
    public Rates Rate { get; set; }
}
public void Main(string args)
{
 string json_mosavab = (new WebClient()).DownloadString("my link");
 var root1 = JsonConvert.DeserializeObject<RootObject_1>(json_mosavab);

string a = "IRR";//For example, the user input is IRR 
Console.WriteLine("IRR IS :" + root1.Rate.(a));//MY error is here
//I wantmy code to work this way
Console.WriteLine("IRR IS :" + root1.Rate.IRR);
}

【问题讨论】:

    标签: c# class object variables syntax


    【解决方案1】:

    试试这个:

    Console.WriteLine("IRR IS :" + root1.Rate.GetType().GetProperty(a).GetValue(root1.Rate, null));
    

    或类似:

    Console.WriteLine("IRR IS :" + typeof(Rates).GetProperty(a).GetValue(root1.Rate, null));
    

    在上面的代码中,首先您要指定对象的类型:

    root1.Rate.GetType()
    

    typeof(Rates)
    

    接下来,通过调用GetProperty,指定要访问的属性名称,可以看出,该方法的输入是string,因此它是用户可以输入的。最后,使用GetValue 方法指定要从中获取指定属性值的对象。

    【讨论】:

      猜你喜欢
      • 2020-08-07
      • 2016-09-14
      • 2020-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-05
      • 1970-01-01
      • 2015-11-11
      相关资源
      最近更新 更多