使用 Blazor 调用 class 失败 "a field initializer cannot reference the nonstatic field, method, or property"

Calling a class with Blazor failing "a field initializer cannot reference the nonstatic field, method, or property"

我刚刚从 Web 窗体开始使用 Blazor,给我留下了深刻的印象。但是,在 Blazor 中调用 class 时,我很难弄清楚我的问题是什么。

正在尝试这样调用:

@code {
testingClass t = new testingClass();
string Teststring = t.TestResponse();
}

有问题的class:

 namespace BlazorTesting.Data
  {
    public class testingClass
    {
        public string TestResponse()
        {
            return "hello world";
        }    
    }
}

问题代码行以及 Visual Studio 表示的错误是:

string Teststring = t.TestResponse();
a field initializer cannot reference the nonstatic field, method, or property 'Component.t'

请注意,我的 Razor 页面上确实有 @using BlazorTesting.Data

这是一个标准的 C# 错误,并非特定于 Blazor。
稍后您将不得不执行 TestResponse(),OnInitialized() 是个好地方。

@code 
{
  testingClass t = new testingClass();
  string Teststring;

  protected override OnInitialzied()
  {
    Teststring = t.TestResponse();
  }
}

注意 null 情况,但对于字符串来说问题不大。

您的问题不是 Blazor 特有的...您无法使用尚不存在的值初始化 Teststring

Instance fields cannot be used to initialize other instance fields outside a method. If you are trying to initialize a variable outside a method, consider performing the initialization inside the class constructor

或者诸如 OnInitialized 生命周期方法之类的方法...

你可以这样做:

@code {
    testingClass t = new testingClass();
    string Teststring => t.TestResponse();

    public class testingClass
    {
        public string TestResponse()
        {
            return "hello world";
        }
    }
}

您也可以像下面的代码片段那样执行此操作,这是首选方式:

@code {
    // Define the variables
    testingClass t;
    string Teststring;

    protected override void OnInitialized()
    {
         // Instantiate your object 
         t = new testingClass();
         // and then use it
        Teststring = t.TestResponse();
    }

    public class testingClass
    {
        public string TestResponse()
        {
            return "hello world";
        }
    }
}