C# return a string from another void
I'm pretty sure this is an easy one. I simply want to return a string from another void.
public static void LinkWorker(string baseURLString)
{
// do some stuff here
HTMLWork(baseURLStringCycle)
--> this is where i need xstring returned
foreach(string xyString in xstring.split('\n'))
{
}
}
public static void HTMLWork(string baseURLStringCycle)
{
//do HTML work here
// create x string
string xString = ; //the result of the htmlwork
}
开发者_运维知识库
You do not want a void
method, you want a method returning type string
.
public static string HTMLWork(string baseURLStringCycle)
{
//...
return xString;
}
There is no way to return a value in a void method, since it is a void method. there are 2 ways to achieve the same result though.
- Use a global variable that is both accessible in both methods. Then, set in the HTMLWork methods the global variable, and access the same variable in LinkWorker method.
- Pass the variable by reference from LinkWorker to HTMLWork. Since the variable is passed by reference, the changes made in HTMLWork will be visible to LinkWorker.
You can't return a string from a void function.
public static void LinkWorker(string baseURLString)
{
// do some stuff here
string xstring=HTMLWork(baseURLStringCycle)
foreach(string xyString in xstring.split('\n'))
{
}
public static string HTMLWork(string baseURLStringCycle) //use string instead of void
{
//do HTML work here
// create x string
string xString = ; //the result of the htmlwork
return xString;
}
If you want to use a Void Method, you should use the Out keyword or pass in a Reference.
e.g.
public static void HTMLWork(string baseUrlStringCyle, out XResult)
{
string xString = "result";
}
why don't you return a string instead of void?
Anthony's Answer is your best bet.
It is also possible to assign a value of a string using an 'out' parameter. But this should not be used when its possible to return directly from the method
eg:
public static void HTMLWork(string baseURLStringCycle, out returnString)
{
returnString = "returned string";
}
Easiest, but obviously not the best way would be to make xString a global
variable.
Other than that unless you have the option of change the HTMLWork method I'm out of options.
You don't want to change function signature and keep this void you can use string as a parameter and change this inside the HTMLWork function. C# pass object as reference so the trick is done.
精彩评论