1

我是 .net 的新手,正在寻找有关如何最好地创建只读对象结构的建议。这些结构是在编译时布局的,根本不会改变。我的对象如下所示:

Public Structure CatPair
    Public code, name As String
End Structure

Public Structure Category
    Public code, name As String
    Public subcategories() As EpfPair
End Structure

Public ReadOnly categories() As Category = {
    New Category With {.code = "Code1", .name = "cat title 1", .subcategories = Nothing
    },
    New Category With {.code = "Code2", .name = "cat title 2", .subcategories = Nothing
    },
    New Category With {.code = "Code3", .name = "cat title 3", .subcategories = Nothing
    },
    New Category With {.code = "Code4", .name = "cat title 4", .subcategories = {
            New CatPair With {.code = "subC1", .name = "subcat title 1"},
            New CatPair With {.code = "subc2", .name = "subcat title 2"},
            New CatPair With {.code = "subc3", .name = "subcat title 3"}
        }
    },
    New Category With {.code = "Code5", .name = "Cat title 5", .subcategories = Nothing
    }
}

所以这个对象实际上是一个嵌套的常量表,其中有些有子类别,有些没有。我的目标是:

  1. 确保所有内容都是只读的,并且
  2. 以某种方式实现它(如果可能的话),这样我的不使用此代码的 ASP.net 页面就不会在每次加载页面时都会产生初始化对象的任何重大开销。我已经在 App_Code 文件夹的模块中声明了该对象,因此我不确定编译器如何处理不接触该对象的页面。
4

1 回答 1

1

您提供的代码不会实现您的目标。要使对象不可变,您至少需要将对象的属性设置为只读(没有设置器),只需将所有内容都传递给构造函数参数。

于 2012-09-03T07:22:57.603 回答