sách gpt4 ai đã đi

c# - 静态集合是否保证在另一个类使用它之前被初始化/填充?

In lại 作者:行者123 更新时间:2023-11-30 19:24:16 31 4
mua khóa gpt4 Nike

假设我有这两个类:

public class A where T : IEntityWithID, new()
{
private static EntityInfo entityInfo = B.GetEntityInfo(typeof(T));

private static IEnumerable TestCases
{
// Do work with entityInfo...
}
}

private static class B
{
private static IList entityInfoList = B.GetEntityList();

public static EntityInfo GetEntityInfo(Type type)
{
return entityInfoList.Single(e => e.Types.Contains(type));
}

private static IList GetEntityList()
{
// Builds a list of EntityInfo's...
}
}

是否保证在类 A 中调用 B.GetEntityInfo() 之前初始化和填充类 B 中的 entityInfoList?

1 Câu trả lời

是的,这是有保证的。这是来自 MSDN 的片段:

The program cannot specify exactly when the class is loaded. However, it is guaranteed to be loaded and to have its fields initialized and its static constructor called before the class is referenced for the first time in your program.

编辑:如前所述,您最终可能会遇到 2 个静态类相互依赖进行初始化的情况,这可能会给您带来麻烦,但只要不是这种情况,您就没事。

关于c# - 静态集合是否保证在另一个类使用它之前被初始化/填充?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38835926/

31 4 0
Bài viết được đề xuất: C regexec 段错误
Bài viết được đề xuất: c - 数据不存储在结构中
Bài viết được đề xuất: javascript - 秒倒计时的 jQuery.countdown 问题
Bài viết được đề xuất: 编译示例 c 文件作为更大的基于 make 的 C 项目的一部分?
行者123
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com