【问题标题】:How to assign to a list from another method in WPF?如何从 WPF 中的另一种方法分配给列表?
【发布时间】:2021-05-18 07:52:31
【问题描述】:

如何从其他方法分配给列表?我创建了 WPF 应用程序。

我试过了:

private static Random number = new Random();
private void count()
{
    int maxfirst = 10;
    int maxsecond = 10;
    int secondc = number.Next(2, maxsecond);
    int firstc = number.Next(1, maxfirst);

    if (mark.Text == "+")
    {
        total = (firstc + secondc);
    }
    else if (mark.Text == "-")
    {
        total = (firstc - secondc);
    }
    else if (mark.Text == "*")
    {
        total = (firstc * secondc);
    }
    else
    {
        firstc = secondc * number.Next(1, maxfirst / secondc);
        int residue = (firstc % secondc);

        if (residue == 0)
        {
            total = (firstc / secondc);
        }
    }
    firstt.Text = firstc.ToString();
    secondt.Text = secondc.ToString();
    result.Text = total.ToString();
}

我有另一种方法:

List<string> list = new List<string> { result.Text, "2", "3" };

我怎样才能获得足够的 result.Text 来列出?它写信给我:编译器错误 CS0236-A 字段初始化程序无法引用非静态字段、方法或属性“字段”。

感谢您的建议和时间。

【问题讨论】:

    标签: c# wpf list


    【解决方案1】:

    编译器告诉你list 是一个字段。 IE。您不是在方法内创建列表,而是作为类的字段。

    由于您使用“字段初始值设定项”,即在声明对象后直接创建对象,因此您不能在类中使用任何其他非静态属性。这是因为这些字段初始化器在构造函数之前运行,因此其他字段,例如 result 可能尚未初始化。

    要解决这个问题,请将您的初始化移动到实际方法或构造函数中。这应该确保它在 result 和其他对象创建之后运行。

    【讨论】:

    • 你是对的,我没有在方法中使用它,我想出了一个不必要的复杂解决方案。非常感谢!!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-16
    • 2017-07-29
    • 1970-01-01
    • 2018-12-24
    • 2012-06-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多