使用Blazor组件:
@page "/counter"
<h1>Counter</h1>
<p>Current count: @_a.CurrentCount</p>
<button class="btn btn-primary" onclick="@_b.IncrementCount">Click me</button>
@functions {
private readonly ClassA _a = new ClassA();
private readonly ClassB _b = new ClassB(_a);
class ClassA
{
public int CurrentCount { get; set; }
}
class ClassB
{
private readonly ClassA _classA;
public ClassB(ClassA classA)
{
_classA = classA;
}
public void IncrementCount() => _classA.CurrentCount++;
}
}
我收到此错误:
错误CS0236字段初始化程序无法引用非静态字段,方法或属性'__Counter._a'
此线程说明如何解决标准类中的此错误:
Why can't you use 'this' in member initializers?
但是为此,它需要一个构造函数。
是否可以在Blazor组件中添加构造函数?
如何解决此错误?
答案 0 :(得分:3)
要使类保持只读状态,您应该移至"code-behind"。然后可以实例化构造函数上的类:
@page "/counter"
@inherits CounterBase
<h1>Counter</h1>
<p>Current count: @_a.CurrentCount ...
CounterBase.cs
using Microsoft.AspNetCore.Blazor.Components;
namespace YourApp.Pages
{
public class ClassA
{
public int CurrentCount { get; set; }
}
public class ClassB
{
private readonly ClassA _classA;
public ClassB(ClassA classA)
{
_classA = classA;
}
public void IncrementCount() => _classA.CurrentCount++;
}
public class CounterBase : BlazorComponent
{
protected readonly ClassA _a;
protected readonly ClassB _b;
//constructor
public CounterBase()
{
_a = new ClassA();
_b = new ClassB(_a);
}
...