I have the following method written in VB.NET:

Public Shared Function formatClassNameAndMethod(ByVal prefix As String, ByVal stackFrame As StackFrame) As String

        Dim methodBase As MethodBase = StackFrame.GetMethod()

        Return prefix + ":[" + stackFrame.GetMethod().DeclaringType.Namespace + "][" + stackFrame.GetMethod().DeclaringType.Name + "." + methodBase.Name + "] "

End Function

I used a code porting tool to convert it to C#. It produced the following method:

public static string formatClassNameAndMethod(string prefix, StackFrame stackFrame)
{
    MethodBase methodBase = StackFrame.GetMethod();

    return prefix + ":[" + stackFrame.GetMethod().DeclaringType.Namespace + "][" + 
            stackFrame.GetMethod().DeclaringType.Name + "." + methodBase.Name + "] ";
}

Unfortunately, Visual Studio now gives me the following error:

Cannot access non-static method 'GetMethod' in static context

It is complaining about StackFrame.GetMethod() because that method is not static. Why is this happening? I understand what the error is, but I don't understand why I didn't get this in VB.NET. Is there a difference between how Shared in VB.NET and static in C# work? Did the conversion tool not properly convert this?

有帮助吗?

解决方案 2

VB is case-insensitive - the compiler saw "StackFrame.GetMethod()" and said "Oh, the developer must have meant "stackFrame.GetMethod()".

其他提示

GetMethod isn't static. This is what it is telling you.

This means you need to create an instance before you can call the method. Your method already has a StackFrame instance passed in.. and this is merely a case of case sensitivity. Lowercase the S.

public static string formatClassNameAndMethod(string prefix, StackFrame stackFrame)
{ //                                                                     ^^^ this
    MethodBase methodBase = stackFrame.GetMethod();
    //                     ^^ lowercase S
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top