我正在尝试使用如下所示的静态构造函数:
public static DataManager()
{
LastInfoID = 1;
}
并且出现了以下错误:
静态构造函数上不允许使用访问修饰符
我想知道我的问题是什么。
我正在尝试使用如下所示的静态构造函数:
public static DataManager()
{
LastInfoID = 1;
}
并且出现了以下错误:
静态构造函数上不允许使用访问修饰符
我想知道我的问题是什么。
静态构造函数没有访问修饰符: 它只是:
static DataManager() // note no "public"
{
LastInfoID = 1;
}
这是因为它从未被显式调用(除非通过反射) - 但是由运行时调用; 访问级别将没有意义。
public
(例如 public class C
);静态构造函数是 private
。你链接的视频是错误的,而且有两个错误:a) 因为它声称它们是公共的(但实际上不是),b) 因为它暗示这是“默认”的,这是没有意义的:这是唯一的选项。 - Marc Gravell.method private hidebysig specialname rtspecialname static void .cctor () cil managed
- 这定义了一个方法(.method
),请注意它既是 static
又是 private
;有一个运行时公认的约定(hidebysig specialname rtspecialname
意味着“查找特殊名称 - 它们不是偶然的”),即 .cctor
是一个特殊名称,用于定义“静态构造函数”(实际上,在 IL 中称为“类型初始化器” - 它可以包括不在 C# 静态构造函数中的代码,例如静态字段初始化器)。 - Marc GravellLastInfoID
字段或属性未声明为静态(static),而您只能从静态构造函数中访问静态成员。同时,请从声明中删除public
关键字:static DataManager()
{
LastInfoID = 1;
}
ListInfoID
不是静态的。 - Guffa去掉public
。静态构造函数的语法为:
class MyClass
{
static MyClass()
{
// Static constructor
}
}
new MyClass();
using System;
public class Something
{
//
private static DateTime _saticConstructorTime;
private DateTime _instanceConstructorTime;
//
public static DateTime SaticConstructorTime
{
set { _saticConstructorTime = value; }
get { return _saticConstructorTime ; }
}
public DateTime InstanceConstructorTime
{
set { _instanceConstructorTime = value; }
get { return _instanceConstructorTime; }
}
//Set value to static propriety
static Something()
{
SaticConstructorTime = DateTime.Now;
Console.WriteLine("Static constructor has been executed at: {0}",
SaticConstructorTime.ToLongTimeString());
}
//The second constructor started alone at the next instances
public Something(string s)
{
InstanceConstructorTime = DateTime.Now;
Console.WriteLine("New instances: "+ s +"\n");
}
public void TimeDisplay(string s)
{
Console.WriteLine("Instance \""+ s + "\" has been created at: " + InstanceConstructorTime.ToLongTimeString());
Console.WriteLine("Static constructor has been created at: " + SaticConstructorTime.ToLongTimeString() + "\n");
}
}
//
class Client
{
static void Main()
{
Something somethingA = new Something("somethingA");
System.Threading.Thread.Sleep(2000);
Something somethingB = new Something("somethingB");
somethingA.TimeDisplay("somethingA");
somethingB.TimeDisplay("somethingB");
System.Console.ReadKey();
}
}
/* output :
Static constructor has been executed at: 17:31:28
New instances: somethingA
New instances: somethingB
Instance "somethingA" has been created at: 17:31:28
Static constructor has been created at: 17:31:28
Instance "somethingB" has been created at: 17:31:30
Static constructor has been created at: 17:31:28
*/
access modifiers
->public
,are not allowed
-> 尝试将其删除。在我看来,C#编译消息非常清晰。如需查找未知术语,请使用Google:http://www.google.nl/search?q=C%23+access+modifiers - Dykam