使用此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++;
}
}
我收到此错误:
此线程说明如何解决标准类中的此错误:
Why can't you use 'this' in member initializers?
但是为此,它需要一个构造函数。
是否可以在Blazor组件中添加构造函数?
如何解决此错误?
最佳答案
要使类保持只读状态,您应该移至"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);
}
...
关于c# - 在Blazor组件中初始化对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54875922/