简体   繁体   中英

“Method must have a return type” and “return must not be followed by an object expression”

Im adding this method to a public static class

    public static LogMessage(Exception ex)
    {
        Trace.WriteLine(ex.ToString());
        return ex; 
    }

When I do this, I get a message that says "method must have a return type"

and in the return I also get a message that says "Since 'Util.logMessage(System.Exception)' returns void, a return keyword must not be followed by an object expression"

How do I correct this?

You would need to change the declaration to return an Exception:

public static Exception LogMessage(Exception ex)
{
    Trace.WriteLine(ex.ToString());
    return ex; 
}

Note that, depending on usage, it might make sense to allow this to be a generic method:

public static T LogMessage<T>(T ex) where T : Exception
{
    Trace.WriteLine(ex.ToString());
    return ex; 
}

This would allow you to use the resulting exception in a strongly typed manner.

Alternatively, you could just not return the exception, since Logging shouldn't need to return an exception in any case:

public static void LogMessage(Exception ex)
{
    Trace.WriteLine(ex.ToString());
}

Your method signature has no return type. Based on the code, I'm guessing you want:

public static Exception LogMessage(Exception ex)
{
    Trace.WriteLine(ex.ToString());
    return ex;
}

Which really makes no sense. There's no reason to return the exception after it's logged. You really could simply do:

public static void LogMessage(Exception ex)
{
    Trace.WriteLine(ex.ToString());
}
public static Exception LogMessage(Exception ex)
{
    Trace.WriteLine(ex.ToString());
    return ex; 
}

If you want to return the exception:

 public static Exception LogMessage(Exception ex)

If void:

 public static void LogMessage(Exception ex)

Any method that has a return must have the return type specified.

Your situation:

public static Exception LogMessage(Exception ex)
{
    Trace.WriteLine(ex.ToString());
    return ex; 
}

If you wanted to return a string:

public static string LogMessage(Exception ex)
{
     return ex.ToString();
}

The void modifier that is seen with methods that have no return is simply stating that the return is of type void . In this case your return would be the type of Exception . A method should always have a return type, whether it is void , a standard type such as string or int , or an object in the type that your class is, such as MyClass . It can also return a generic such as List<T> or object .

In this case though, as others have stated, it really does not make sense to return an exception.

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