Field initializer 需要的解决方案不能引用 Blazor 中的非静态字段方法或属性 [英] Solution needed for Field initializer cannot reference the non-static field method or property in Blazor

查看:49
本文介绍了Field initializer 需要的解决方案不能引用 Blazor 中的非静态字段方法或属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个 Blazor 项目,但我的问题是 C#.我确实理解这个问题,但我无法在 Blazor 上下文中解决它.

I'm working on a Blazor project, but my problem is C#. I do understand the problem, but I just can not solve it in the Blazor context.

在我的剃刀页面中,我使用了一个以 x 轴为日期的 blazorise 折线图.如果我使用非动态日期,那效果很好.

In my razor page I use a blazorise linechart that takes dates for the x-axis. That works perfectly well if I use non-dynamic dates. The

但是,要动态确定日期(因此是 x 轴标签),我需要后面的代码:

However, to determine the dates (so the x-axis labels) dynamically, I need the following code behind:

public partial class ChartComponent : ComponentBase
    {    
        [Parameter]
        public List<Observation> Observations { get; set; }     //an Observation has a field with a Date in it. 

        Object options = new            
        {
            Scales = new
            {
                XAxes = new[]
                {
                    new
                    {
                        labels =   new[]{GetDateTimeLabels()}   //this gets me the error, if I use new[]{DateTime.Now,...,DateTime.Now+n} it works just fine.
                    }
                }
            }
        };


public DateTime[] GetDateTimeLabels()
        {
            DateTime[] dateLabels = VACRAObservations.Select(x => x.Date).ToArray();
            return dateLabels;
        }

这让我得到一个错误字段初始值设定项不能引用非静态字段方法或属性",这是我理解的,因为编译器不知道在对象选项初始化之前 GetLabels() 是否准备就绪.

This gets me an error "a field initializer cannot reference the non-static field method or property", which I understand, because the compiler does not know if GetLabels() is ready before Object options is initialized.

我无法绕过 [Parameter],我需要它将观察列表放入剃刀页面.

I cannot go around the [Parameter], I need it to get the list of Observations into the razor page.

我试图把它全部放在构造函数中,但是构造函数在参数被取入之前被初始化.

I tried to put it all in the constructor, but the constructor is initialized before the parameter is taken in.

我尝试用静态来实现,但静态类不能从 Componentbase 类派生.

I tried to do it with statics, but a static class can not derive from Componentbase class.

我不知道该怎么办.如果您需要更多信息,请告诉我.

I'm at a loss what to do. Please let me know if you need more information.

推荐答案

最简单的解决方法是将其设为属性.当你只需要它一次时,添加一个 > :

The easiest fix is to make it a property. When you only need it once, add a > :

 Object options => new   {  ...  };         

以及当您需要避免过于频繁地对其进行评估时:

and when you need to guard against evaluating it too often:

 Object _options = null;
 Object options => _options ?? (_options = new            
    {
        ... // as before
    });

这篇关于Field initializer 需要的解决方案不能引用 Blazor 中的非静态字段方法或属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆