“Expected class, delegate, enum, interface or struct” error on public static string MyFunc(). What's an alternative to “string”?

生来就可爱ヽ(ⅴ<●) 提交于 2019-11-30 17:56:23

You need to put the method definition into a class/struct definition. Method definitions can't appear outside those.

There is a capital S String in C#/.Net - System.String. But that is not your problem. @Femaref got it right - this error is indicating that your method is not part of a class.

C# does not support standalone functions, like C++ does. All methods have to be declared within the body of a class, interface or struct definition.

kayleeFrye_onDeck

I ran into this problem when getting re-acquainted with P-Invoke. Femaref had it right. Here's some sample code for quick visualization purposes:

Working Code:

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)
        {

        }
    }
}

Broken Code:

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)
        {

        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!