简体   繁体   中英

Return value or out parameter for c# method that can return either a char or string?

I ran across some code during a code review that didn't seem right, but not sure the "best" way to change it. In looking for an a answer I found which is better, using a nullable or a boolean return+out parameter and Which is better, return value or out parameter? The latter had a answer with this comment that I generally agree with:

If you find yourself needing to return two things from an API then wrapping them up in a struct/class would be better than an out param."

Here is a representative sample of the code in question. It's part of a web application and basically loops through a character buffer and wants to translate "unprintable" characters to either a replacement character or string. To do this, the author of the Translate method always returns a string and the caller has to convert back to a character array.

string character = Translate(value);
if (character.Length == 1) {
    writer.Write(character[0]);
} else {
    writer.Write(character.ToCharArray());
}

public string Translate(char value) {
    if (value <= '\u017F') {
        return value.ToString();
    }

    switch (value) {
        case '\u2117':
            return '\u00A9'.ToString();  // copyright sign
        case '\u211E':
            return "Rx"; // prescription
        // ... and lots more case statements
    }

    return value.ToString();
}

It seemed to me I have a couple options. Do I make the caller infer which char or string to use based on null or String.Empty values, or be explicit with an out bool? I don't want to new up and return a tuple object instance for every char that passes through this function, since that seems like a lot of object creation overhead and future garbage collection.

public string Translate(char value, out char newValue)
public void Translate(char value, out char? newCharValue, out string newStringValue)
public void Translate(char value, out bool useChar, out char newCharValue, out string newStringValue)

总是返回一个字符串(长度为0、1或很多),并总是调用writer.Write(string)呢?

如果返回字符串,为什么不使用“ \\ u00A9”而不是'\\ u00A9'.ToString()?

Are you expecting to use this Translate method stand-alone anywhere, or is it always going to be used for the purpose of writing one stream's data to another? How about passing the writer to the Translate method, and letting it call the appropriate writer.Write method?

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