Tho*_*yme 2 c# static initialization const
我正在尝试创建一个自定义类的常量静态集合,如下所示:
public class MyClass
{
public string Property1 { get; set; }
public string Property2 { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
然后创建一类MyClass的常量静态对象
static class MyObjects
{
public const MyClass anInstanceOfMyClass = { Property1 = "foo", Property2 = "bar" };
}
Run Code Online (Sandbox Code Playgroud)
但是编译器抱怨在当前上下文中不存在名称"Property1"和"Property2".当我这样做时:
public const MyClass anInstanceOfMyClass = new MyClass() { Property1 = "foo", Property2 = "bar" };
Run Code Online (Sandbox Code Playgroud)
编译器抱怨Property1和Property2是只读的.如何正确初始化这些MyClass对象的常量静态类?
试试这个:
public static readonly MyClass AnInstanceOfMyClass = new MyClass() { Property1 = "foo", Property2 = "bar" };
Run Code Online (Sandbox Code Playgroud)
注意static class MyObjects没有访问修饰符.默认是internal.如果你打算在同一个程序集中使用它,你会没事的,但如果你打算在程序集之外使用这个帮助程序类,你需要使用public关键字,如下所示:
public static class MyObjects
{
public static readonly MyClass AnInstanceOfMyClass = new MyClass() { Property1 = "foo", Property2 = "bar" };
}
Run Code Online (Sandbox Code Playgroud)
请注意,根据Microsoft对C#命名约定的建议,我使用Pascal案例作为静态属性.
除上述评论外,您还可以在此处找到有关readonly和const关键字的更多信息: