简体   繁体   中英

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 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.

When I run this code I get this error:

Cannot implicitly convert type 'object' to '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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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