gpt4 book ai didi

c# - Lambda 表达式的位置在延迟初始化中是否重要?

转载 作者:太空狗 更新时间:2023-10-29 22:32:08 24 4
gpt4 key购买 nike

我尝试了延迟初始化 sample code来自MSDN。我尝试使用 lambda 表达式通过静态 Func< T > 委托(delegate)来模拟静态 InitLargeObject() 方法,因为 Lazy< T > 构造函数可以接受它。

static Lazy<LargeObject> lazyLargeObject = new Lazy<LargeObject>(InitWithLambda);

static Func<LargeObject> InitWithLambda = () =>
{
LargeObject large = new LargeObject(Thread.CurrentThread.ManagedThreadId);
// Perform additional initialization here.
return large;
};


static LargeObject InitLargeObject()
{
LargeObject large = new LargeObject(Thread.CurrentThread.ManagedThreadId);
// Perform additional initialization here.
return large;
}

static void Main()
{

//lazyLargeObject = new Lazy<LargeObject>(InitLargeObject); // <---- This one use the static method.
lazyLargeObject = new Lazy<LargeObject>(InitWithLambda); // <---- Thsi one uses the lambda expression.


Console.WriteLine(
"\r\nLargeObject is not created until you access the Value property of the lazy" +
"\r\ninitializer. Press Enter to create LargeObject.");
Console.ReadLine();

// Create and start 3 threads, each of which uses LargeObject.
Thread[] threads = new Thread[3];
for (int i = 0; i < 3; i++)
{
threads[i] = new Thread(ThreadProc);
threads[i].Start();
}

// Wait for all 3 threads to finish.
foreach (Thread t in threads)
{
t.Join();
}

Console.WriteLine("\r\nPress Enter to end the program");
Console.ReadLine();
}

如果我将 InitWithLambda 委托(delegate)放在 lazyLargeObject 声明之前,一切都很好。

如果我将 InitWithLambda 委托(delegate)放在 lazyLargeObject 声明之后,我会收到此错误:

Unhandled Exception: System.TypeInitializationException: The type initializer for 'Program' threw an exception. ---> System.ArgumentNullException: Value cannot be null. Parameter name: valueFactory at System.Lazy1..ctor(Func1 valueFactory, LazyThreadSafetyMode mode) at System.Lazy1..ctor(Func1 valueFactory) at Program..cctor() in E:\myCode\Misc\LazyWithLambda\LazyWithLambda\Class1.cs:line 10 --- End of inner exception stack trace --- at Program.Main()

lambda 表达式似乎未能分配给 valueFactory 参数。

但似乎位置不影响 InitLargeObject() 方法,它没有使用 Lambda 表达式。

为什么?

更新1

根据 Billy ONeal ,我用更简单的代码解决了这个问题:

这个没问题:

class FieldInitInOrder
{
static string s1 = "abc";
static Int32 s1_length = s1.Length;

static void Main()
{
Console.WriteLine(s1_length);
}
}

这个抛出相同的 NullReference 异常:

class FieldInitInOrder
{
static Int32 s1_length = s1.Length; // Order switched
static string s1 = "abc"; // Order switched

static void Main()
{
Console.WriteLine(s1_length);
}
}

我不知道为什么C#编译器是这样设计的。它可能会导致非常微妙的错误。有没有设计上的考虑?

最佳答案

C# 按照声明的顺序初始化成员。

关于c# - Lambda 表达式的位置在延迟初始化中是否重要?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24587523/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com