在C#中评估字符串表达式 [英] Evaluate string expression in C#

查看:152
本文介绍了在C#中评估字符串表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下字符串表达式尝试运行,但是收到错误说字符串格式不正确



I have the following string expression which am trying to run ,But am getting error saying string format is not correct

var result = new List<XYZ>();

public class XYZ
{
  public String  Timezone {get;set;}
  public Decimal? B1Volume { get; set; }
  public Decimal? B2Volume { get; set; }
  public Decimal? B3Volume { get; set; }
public Decimal? B4Volume { get; set; }
  public Decimal? B5Volume { get; set; }
  .............
  .............
 public Decimal? B24Volume { get; set; }
}

for (i = diffvol; i < result.count; i++)
{
    B1Volume = Convert.ToDecimal(String.Format("result[0].B{0}Volume", i));
   
}





我的尝试:





What I have tried:

var london = TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time");
                var googleplex = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
                var now = DateTimeOffset.UtcNow;
                TimeSpan londonOffset = london.GetUtcOffset(now);
                TimeSpan googleplexOffset = googleplex.GetUtcOffset(now);
                TimeSpan difference = londonOffset - googleplexOffset;

for (i= diffvol.hours;i< result.count; i++)
{
   //Code to implement

}

推荐答案

看看你想做什么:

Look at what you are trying to do:
B1Volume = Convert.ToDecimal(String.Format("result[0].B{0}Volume", i));

您要转换的字符串将是

The string you are trying to convert will be

result[0].B0Volume

然后

Then

result[0].B1Volume




result[0].B2Volume

依此类推。其中任何一个都不能转换为十进制值,这正是错误消息告诉你的。

假设您的代码在循环中并且只使用最终值,我将创建一个返回单个值的方法,并使用开关选择从哪个变量返回值。

And so on. None of which are convertible to decimal values, which is exactly what the error message is telling you.
given that your code is inside a loop and only the final value will be used, I'd create a method to return the single value and use a switch to select which variable to return the value from.


是的,你不能像执行C#代码一样执行字符串。这不会起作用。



显示你想要做的事情并提供一些示例数据。
Yeah, you can't execute a string as if it was C# code. That's not going to work.

Show what you're trying to do with this and give some example data.


这篇关于在C#中评估字符串表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆