字段初始值设定项不能引用非静态字段、方法或属性? [英] A field initializer cannot reference the non-static field, method, or property?

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

问题描述

我有一个存储库类和一个服务类,如下所示:

I have a Repository Class and a Services Class as below :

public class DinnerRepository
{
    DinnerDataContext db = new DinnerDataContext();

    public Dinner GetDinner(int id)
    {
        return db.Dinners.SingleOrDefault(d => d.DinnerID == id);   
    }

// Others Code        
}



public class Service
{
        DinnerRepository repo = new DinnerRepository(); 
        Dinner dinner = repo.GetDinner(5);

// Other Code
}

这会引发错误:

字段初始值设定项不能引用非静态字段、方法或属性.

A field initializer cannot reference the non-static field, method, or property.

即使我已经初始化了 DinnerRepository 类以在服务类中公开其方法 GetDinner().这适用于以下代码.有没有其他替代方法或者它是标准做法?我这里不能使用静态方法..

Even though I have intatiated the DinnerRepository Class to expose its method GetDinner() in the Service Class. This works fine with below code. Is there any alternative to it or is it a standard practice? I cannot use static methods here..

public class Service
{

    public Service()
    {
        DinnerRepository repo = new DinnerRepository(); 
        Dinner dinner = repo.GetDinner(5);
    }

}

推荐答案

我个人只是在构造函数中初始化字段:

Personally I'd just initialize the fields in a constructor:

public class Service
{
    private readonly DinnerRepository repo;
    private readonly Dinner dinner;

    public Service()
    {
        repo = new DinnerRepository();
        dinner = repo.GetDinner(5);
    }
}

请注意,这与您在问题底部显示的代码不同,因为它只是声明了本地变量.如果您只想要局部变量,那没问题——但如果您需要实例变量,则使用上述代码.

Note that this isn't the same as the code you show at the bottom of the question, as that's only declaring local variables. If you only want local variables, that's fine - but if you need instance variables, then use code as above.

基本上,字段初始值设定项的功能有限.来自 C# 4 规范的第 10.5.5.2 节:

Basically, field initializers are limited in what they can do. From section 10.5.5.2 of the C# 4 spec:

实例字段的变量初始值设定项不能引用正在创建的实例.因此,在变量初始值设定项中引用 this 是编译时错误,因为变量初始值设定项通过 simple-name.

A variable initializer for an instance field cannot reference the instance being created. Thus it is a compile-time error to reference this in a variable initializer, because it is a compile-time error for a variable initializer to reference any instance member through a simple-name.

(因此"和因此"在我看来是错误的 - 通过简单名称引用成员是非法的因为它引用了this -我会向 Mads 询问这件事 - 但这基本上是相关部分.)

(That "thus" and "therefore" looks the wrong way round to me - it's illegal to reference a member via a simple-name because it references this - I'll ping Mads about it - but that's basically the relevant section.)

这篇关于字段初始值设定项不能引用非静态字段、方法或属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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