公共静态字符串MyFunc()上的“预期的类,委托,枚举,接口或结构”错误。 什么是“字符串”的替代品?

我尝试使用以下静态函数时收到错误。

错误:

预期的类,委托,枚举,接口或结构

function(和类):

namespace MyNamespace { public class MyClass { // Some other static methods that use Classes, delegates, enums, interfaces, or structs public static string MyFunc(string myVar){ string myText = myVar; //Do some stuff with myText and myVar return myText; } } } 

这导致编译器愤怒地(红色)为public static string的字符串部分加下划线。

所以,我认为这意味着string不是类,委托,枚举,接口或结构。

我可以使用什么而不是string来返回字符串或类似字符串的对象? 在C#中似乎没有String (大写字母S)类。

编辑 :括号与某些注释代码不匹配 – 上面的代码工作正常,我的实际不匹配代码没有。 谢谢!

您需要将方法定义放入类/结构定义中。 方法定义不能出现在那些之外。

C#/。Net – System.String有一个大写S String。 但这不是你的问题。 @Femaref做对了 – 这个错误表明你的方法不属于类。

C#不支持像C ++那样的独立函数。 所有方法都必须在类,接口或结构定义的主体内声明。

我在重新认识P-Invoke时遇到了这个问题。 Femaref做对了。 以下是一些用于快速可视化目的的示例代码:

工作守则:

 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Runtime.InteropServices; namespace ConsoleApplication2 { class Program { [DllImport("kernel32.dll", CharSet = CharSet.Auto)] public static extern IntPtr GetModuleHandle(string lpModuleName); static void Main(string[] args) { } } } 

破碎的代码:

 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Runtime.InteropServices; [DllImport("kernel32.dll", CharSet=CharSet.Auto)] public static extern IntPtr GetModuleHandle(string lpModuleName); namespace ConsoleApplication2 { class Program { static void Main(string[] args) { } } }