【发布时间】:2012-01-24 01:38:30
【问题描述】:
我正在尝试创建自定义类的常量静态集合,如下所示:
public class MyClass
{
public string Property1 { get; set; }
public string Property2 { get; set; }
}
然后创建一个类的常量,MyClass 的静态对象
static class MyObjects
{
public const MyClass anInstanceOfMyClass = { Property1 = "foo", Property2 = "bar" };
}
但编译器抱怨名称“Property1”和“Property2”在当前上下文中不存在。当我这样做时:
public const MyClass anInstanceOfMyClass = new MyClass() { Property1 = "foo", Property2 = "bar" };
编译器抱怨 Property1 和 Property2 是只读的。如何正确初始化这些 MyClass 对象的常量静态类?
【问题讨论】:
标签: c# static initialization constants