不能访问非静态字段 [英] Cannot access non-static field

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

问题描述

我想不通为什么它寻找一些静态的:

I can't figure out why it's looking for something static:

public class DatabaseBase
{
    private readonly string connectionString;

    public DatabaseBase(string connectionString)
    {
        this.connectionString = connectionString;
    }
}

public class MyDB : DatabaseBase
{
    readonly string connectionString = ConfigurationManager.AppSettings["MyConnectionString"];

    public MyDB() : base(connectionString)
    {          
    }
}

我得到了静态情况下不能访问非静态字段'的connectionString。我没有看到任何静态的基础数据库类,为什么?

I get Cannot access non-static field 'connectionString' in static context. I don't see anything static in the base Database class so why??

这里的时候,我们做了还挺同样的事情的另一个例子:

here's another example of when we did kinda the same thing:

partial class Database : DatabaseBase
{
    static string DbConnectionString
    {
        get
        {
            if (dbConnectionString == null)
                dbConnectionString = 
                    ConfigurationManager.AppSettings["MyConnectionString"];
            return dbConnectionString;
        }
    }
    public Database() :base(DbConnectionString)
    {
    }

确定,所以为什么它必须是一个静态的字符串传递连接字符串?

ok so why did it have to be a static string for the connection string to be passed?

推荐答案

我们一直在努力给予了准确的错误信息,所以请仔细阅读。该错误信息是告诉你到底是怎么回事错误:您在上下文访问非静态字段它是唯一合法的访问静态

We have worked hard to give error messages that are accurate, so read them carefully. The error message is telling you exactly what is going wrong: you are accessing a non-static field in a context where it is only legal to access statics.

那么,为什么是一个基构造函数调用的参数列表上下文它是唯一合法的访问静态?

So why is a base constructor call argument list a context where it is only legal to access statics?

当你调用基类的构造,你传递参数的不能引用本的。为什么?因为无论是派生的构造函数也不是为基构造你的本尚未运行,因此这几乎可以肯定不一致,部分初始化的状态。这是疯狂的错误的秘诀。因此,我们访问这个直到我们知道,最起码,基本构造函数运行限制你。

When you call a base constructor, the arguments you pass must not reference "this". Why? Because neither the derived constructor nor the base constructor for your "this" has run yet, and therefore "this" is almost certainly in an inconsistent, partially-initialized state. That is a recipe for crazy bugs. We therefore restrict you from accessing "this" until we know that at the very least, the base constructor has run.

此功能鼓励合理,秩序井然,理解,维护和无缺陷的建筑逻辑;我建议有工作,不反对,这些保障措施。

This feature encourages sensible, well-ordered, understandable, maintainable and bug-free construction logic; I recommend working with, not against, those safeguards.

这篇关于不能访问非静态字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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