2011-01-28 60 views
12

當我嘗試使用以下靜態函數時,出現錯誤。公共靜態字符串MyFunc()上的「期望的類,委託,枚舉,接口或結構」錯誤。什麼是「字符串」的替代?

錯誤:

Expected class, delegate, enum, interface, or struct

功能(和類):

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)類。

編輯:括號與一些註釋代碼不匹配 - 上面的代碼工作正常,我的實際不匹配的代碼沒有。謝謝!

回答

24

您需要將方法定義放入類/結構體定義中。方法定義不能出現在這些之外。

+0

(我認爲)那是。更新代碼以包含這些詳細信息... – Peach 2011-01-28 02:17:05

+4

而且我很確定它不是,至少我沒有遇到任何其他原因導致的特定編譯器錯誤。檢查你的大括號,這也可能是一個原因。 – Femaref 2011-01-28 02:19:19

4

在C#/ .Net中有一個大寫的S字符串 - System.String。但那不是你的問題。 @Femaref說得對 - 這個錯誤表明你的方法不是類的一部分。

C#不支持獨立函數,就像C++一樣。所有方法都必須在類,接口或結構定義的主體中聲明。

0

當我重新熟悉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) 
     { 

     } 
    } 
}