简体   繁体   English

如何将Shared VB.NET方法转换为C#

[英]How to convert Shared VB.NET method to C#

I have the following method written in VB.NET: 我用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#. 我使用了代码移植工具将其转换为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: 不幸的是,Visual Studio现在给我以下错误:

Cannot access non-static method 'GetMethod' in static context 在静态上下文中无法访问非静态方法“ GetMethod”

It is complaining about StackFrame.GetMethod() because that method is not static. 它抱怨StackFrame.GetMethod()因为该方法不是静态的。 Why is this happening? 为什么会这样呢? I understand what the error is, but I don't understand why I didn't get this in VB.NET. 我知道错误是什么,但是我不明白为什么我没有在VB.NET中得到这个错误。 Is there a difference between how Shared in VB.NET and static in C# work? VB.NET中的Shared和C#中的static如何工作之间有区别? Did the conversion tool not properly convert this? 转换工具没有正确转换吗?

GetMethod isn't static. GetMethod不是静态的。 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. 您的方法已经传递了一个StackFrame实例。这只是区分大小写的情况。 Lowercase the S . S小写。

public static string formatClassNameAndMethod(string prefix, StackFrame stackFrame)
{ //                                                                     ^^^ this
    MethodBase methodBase = stackFrame.GetMethod();
    //                     ^^ lowercase S

VB不区分大小写-编译器看到“ StackFrame.GetMethod()”,并说“哦,开发人员一定要使用“ stackFrame.GetMethod()”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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