简体   繁体   English

c#从字符串转换为特殊类型-“存在显式转换”

[英]c# Converting from string to special type - “an explicit conversion exists”

Outputs.RunParams.RunAlgorithm = Convert.ChangeType(AlgString,typeof(RunAlgorithmConstants));

I'm trying to set a Run Parameter for a program to a specific value, but the AlgString is a string and I need it to be of the type RunAlgorithmConstants. 我正在尝试将程序的运行参数设置为特定值,但是AlgString是字符串,我需要将其设置为RunAlgorithmConstants类型。 AlgString being a string is a result of converting from type RunAlgorithmConstants to string directly in a previous script, saving it to a text file, reading from that text file, and setting the text to AlgString. AlgString是字符串是在先前的脚本中直接从RunAlgorithmConstants类型转换为字符串,将其保存到文本文件,从该文本文件读取并将文本设置为AlgString的结果。

When I run this code I get this error: 当我运行此代码时,出现以下错误:

Cannot implicitly convert type 'object' to 'RunAlgorithmConstants'. 无法将类型'object'隐式转换为'RunAlgorithmConstants'。 An explicit conversion exists (are you missing a cast?) 存在显式转换(您是否缺少演员表?)

The namespace is fine. 命名空间很好。 I could write 我可以写

if (AlgString.Equals("Example1"))
{
Outputs.RunParams.RunAlgorithm = RunAlgorithmConstants.Example1
}

for every possible value that RunAlgorithmConstants could be but I was wondering if there is an easier way. 对于RunAlgorithmConstants可能的每个可能值,但我想知道是否有更简单的方法。

Edit: 编辑:

int LineNumber = Inputs.LineNumber;


var lines = File.ReadAllLines(Inputs.LoadLocation);


string line = lines[LineNumber];


{char[] delimiterChars = {','};


  string[] words = line.Split(delimiterChars);
  words[30] = AlgString

Enum.Parse是您在寻找什么:

Outputs.RunParams.RunAlgorithm = (RunAlgorithmConstants) Enum.Parse(typeof(RunAlgorithmConstants), AlgString);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM