gpt4 book ai didi

c# - 如何使用初始化语法在新语句中使用类字段

转载 作者:太空宇宙 更新时间:2023-11-03 22:47:02 24 4
gpt4 key购买 nike

<分区>

我有一个要实例化的类。它包含两个字段,一个是String,另一个是Action。

在 Action 语句中,我想在我的类中使用字符串字段。但是,我不知道如何在实例化时直接调用它。有什么办法,还是我必须创建一个字段来包含实例化的类,然后调用文本?

public class ExampleClass
{
public string text;
public Action action;
// on class instantiate -> action.Invoke();
}

public class Program
{
static void Main(string[] args)
{
new ExampleClass
{
text = "Hello",
action = () => {
/* use the text element we specified to do something ->
e.g Console.WriteLine(text); */ },
};
Console.ReadLine();
}
}

尝试仅使用 text 字段(如 action => ()=> {Console.WriteLine(text);})会导致错误:

CS0103 The name 'text' does not exist in the current context

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