如何通过变量名访问 C# struct 属性?

Posted

技术标签:

【中文标题】如何通过变量名访问 C# struct 属性?【英文标题】:How to access C# struct property by variable name? 【发布时间】:2021-07-22 14:35:48 【问题描述】:

如何根据用户在运行时定义的字符串变量访问结构的属性?

我知道这并不理想。这只是一个简单的任务。

我想使用枚举,但据我了解,我不支持存储 double 类型的值。

如果还有其他最佳做法可以使用,请同时提出建议。

感谢您的帮助!

using System;

public struct Rates

   
public const double charterdaily = 1000;
public const double charterhourly = 400;
public const double charterdistance = 3.5;
public const double minibusdaily = 925;
public const double minibushourly = 360;
public const double minibusdistance = 3.25;
public const double sprinterdaily = 850;
public const double sprinterhourly = 320;
public const double sprinterdistance = 3;
public const double partybusdaily = 1000;
public const double partybushourly = 400;
public const double partybusdistance = 3.5; 
public const double sedandaily = 7000;
public const double sedanhourly = 240;
public const double sedandistance = 2.5;
public const double suvdaily = 625;
public const double suvhourly = 200;
public const double suvdistance = 2.25; 
public const double limodaily = 550;
public const double limohourly = 400;
public const double limodistance = 3.5;


public class Program

    public static void Main(string[] args)
    
       
        int numberOfVehicles;
        Console.WriteLine("Enter # of vehicles: ");
        numberOfVehicles = Convert.ToInt32(Console.ReadLine());

        string vehicleType;
        Console.WriteLine("Enter vehicle type. Values accepted: charter, minibus, sprinter, partybus, sedan, suv, limo.");
        vehicleType = Console.ReadLine().ToLower();

        string pricingMethod;
        Console.WriteLine("Enter pricing method. Values accepted: daily, hourly, distance.");
        pricingMethod = Console.ReadLine().ToLower();

        double pricingMethodUnits; //double because we want to support partial mile distances


 switch (pricingMethod)
      
          case "daily":

              Console.WriteLine("Enter number of DAYS you are renting: ");
              pricingMethodUnits = Convert.ToDouble(Console.ReadLine());
              break;
          
          case "hourly":

              Console.WriteLine("Enter number of HOURS you are renting:");
              pricingMethodUnits = Convert.ToDouble(Console.ReadLine());
              break;

          case "distance":

              Console.WriteLine("Enter expected DISTANCE traveled in miles: ");
              pricingMethodUnits = Convert.ToDouble(Console.ReadLine());
              break;


          default:
              Console.WriteLine("Invalid pricing method value entered");            
              
              break;
      


        string enumString = vehicleType + pricingMethod;
        Console.WriteLine("enumString value: " + enumString );
        
        //this is where I want to access the Rate struct by the passed in enum string
        Console.WriteLine(Rates."enumString");
     
    
```

【问题讨论】:

您是否考虑过使用Dictionary<string, double>?你可以在构造函数的某个地方填充它,然后你可以做double rate = rateLookup[enumString]; 为什么不直接创建一个带有属性的Vehicle 类并将它们放入一个列表中呢?为什么要/需要使用结构? 【参考方案1】:

我建议使用static Dictionary<string, double>:

  private static readonly IReadOnlyDictionary<string, double> Rates =
    new Dictionary<string, double>(StringComparer.OrdinalIgnoreCase) 
       "charterdaily",  1000,
       "charterhourly", 400,
      //TODO: Add all the pairs here
    ;

然后你可以通过它的键从字典中读取值

  //this is where I want to access the Rate struct by the passed in enum string
  Console.WriteLine(Rates[enumString]);

【讨论】:

【参考方案2】:

使用以下代码行动态选择结构属性值:

 // Your sample code 
 string enumString = vehicleType + pricingMethod;
    Console.WriteLine("enumString value: " + enumString );
 
 // Code to get the values
 var data = typeof(Rates).GetFields().Where(x=>x.Name==enumString)
                 .Select(a => a.GetRawConstantValue()
                 .ToString()).ToArray().FirstOrDefault();

【讨论】:

这可能正常工作,但是需要“双精度类型的值”(引自问题)。

以上是关于如何通过变量名访问 C# struct 属性?的主要内容,如果未能解决你的问题,请参考以下文章

Vue 3 通过变量名访问对象属性

java--面向对象---访问属性

变量的概念

当前对象this

Swift 如何访问 Struct 对象字典中的特定变量

C#如何在form1中显示Form2中的变量?