如何将共享的 VB.NET 方法转换为 C#
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19283482/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert Shared VB.NET method to C#
提问by gonzobrains
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#. It produced the following method:
我使用代码移植工具将其转换为 C#。它产生了以下方法:
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. 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?
它抱怨是StackFrame.GetMethod()
因为该方法不是静态的。为什么会这样?我明白错误是什么,但我不明白为什么我没有在 VB.NET 中得到这个。VB.NET 中的 Shared 和 C# 中的 static 的工作方式有区别吗?转换工具没有正确转换这个吗?
采纳答案by Dave Doknjas
VB is case-insensitive - the compiler saw "StackFrame.GetMethod()" and said "Oh, the developer must have meant "stackFrame.GetMethod()".
VB 不区分大小写 - 编译器看到“StackFrame.GetMethod()”并说“哦,开发人员一定是指“stackFrame.GetMethod()”。
回答by Simon Whitehead
GetMethod
isn't static. This is what it is telling you.
GetMethod
不是静态的。这就是它告诉你的。
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.
这意味着您需要先创建一个实例,然后才能调用该方法。您的方法已经StackFrame
传入了一个实例......这只是区分大小写的情况。小写S。
public static string formatClassNameAndMethod(string prefix, StackFrame stackFrame)
{ // ^^^ this
MethodBase methodBase = stackFrame.GetMethod();
// ^^ lowercase S