字段初始值设定项无法引用非静态字段,方法或属性“FullmessageController.readsql”

时间:2018-04-05 09:11:06

标签: c#

我收到错误:

  

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

在以下代码块中:

ReadSQL readsql = new ReadSQL();
QueryHandler queryhandler = new QueryHandler(readsql);

Query处理程序如下所示:

IReadSQL _readsql;
public QueryHandler(IReadSQL readsql)
{
    _readsql = readsql;
}

ReadSQL看起来像这样:

public class ReadSQL : IReadSQL
{
    public string GetSQLContent(string name)
    {
        Assembly assembly = Assembly.GetExecutingAssembly();
        string location = "ProofofconceptAPI.Classes.Queries." + name;

        using(Stream stream = assembly.GetManifestResourceStream(location))
        {
            using(StreamReader streamreader = new StreamReader(stream))
            {
                return streamreader.ReadToEnd();
            }
        }
    }
}

为什么会出错,我该如何解决?

2 个答案:

答案 0 :(得分:0)

正如@ aluan-haddad所提到的,我必须在我的构造函数中初始化它,如下所示:

QueryHandler queryhandler = new QueryHandler(new ReadSQL());

答案 1 :(得分:0)

这里的正确方法取决于您是否真的需要多个字段。如果你想要两个字段,一个用于App\Employee {#1183 id: 7, name: "John Doe", avatar: null, salary: 20000, insurance: 4000, created_at: "2018-03-28 10:15:00", updated_at: "2018-04-06 03:56:48", user_id: null, pivot: Illuminate\Database\Eloquent\Relations\Pivot {#1172 company_id: 1, employee_id: 7, employee_role: 3, **employee_role_name: "Manager"** }, }, ,一个用于ReadSQL,你可以这样做,初始化构造函数中的字段:

QueryHandler

如果您只需要一个字段(对于// Names adjusted for convention class Whatever { private ReadSql readSql; private QueryHandler queryHandler; public Whatever() { readSql = new ReadSql(); queryHandler = new QueryHandler(readSql); } } ),那么您可以在字段初始值设定项中内联QueryHandler

ReadSQL