非静态字段、方法或 属性 需要对象引用

An object reference is required for the non-static field, method, or property

我已经创建了 class 名称 cls1 并创建了名为 GrantAccess() 的方法。但是我无法访问 _entities.it 并显示以下错误 "Error 1 An object reference is required for the non-static field, method, or property 'Path._entities".

public class cls1 
{
    private readonly DBEntities _entities;

    public cls1 ()
    {
        if (_entities == null)
        {
            _entities = new DBEntities();
        }
    }

    public static void GrantAccess()
    {
        if (Settings.DbLog == "1")
        {
            _entities.II_CCLog("Excuting the GrantAccess() Method");
        }
    }
}  

上述方法在其他class.

中被调用
 public void GetCConfig()
 {
 cls1.GrantAccess();
 }

首先,您必须在 class 中创建一个 cls1 对象,您将在其中调用 cls1 class 的方法,然后使用该对象引用,您将能够调用该方法GrantAccess();。您可以通过以下方式创建对象:-

variable_name = new class_name( );

GrantAccess 是静态方法,而 _entities 不是静态变量。所以你需要让 GrantAccess 成为一个非静态方法或者你必须让 _entities 成为一个静态变量。

Static methods and properties cannot access non-static fields and events in their containing type, and they cannot access an instance variable of any object unless it is explicitly passed in a method parameter.

或者在静态 GrantAccess 方法中创建一个 DEBentities 的新实例,并在该实例上执行您的操作。

public static void GrantAccess()
{
    if (Settings.DbLog == "1")
    {
        DBEntities entities = new DBEntities();
        entities.II_CCLog("Excuting the GrantAccess() Method");
    }
}

您将静态代码与实例代码混合在一起。如果您正在使用对象,请不要将您的方法 GrantAccess 设为静态:

public void GrantAccess()
{
    if (Settings.DbLog == "1")
    {
        _entities.II_CCLog("Excuting the GrantAccess() Method");
    }
}

然后您必须创建 cls1 的实例:

public void GetCConfig()
{
    var instance = new cls1();
    cls1.GrantAccess();
}

您还应该使 cls1 成为一次性的,并在您使用完后在 _entities 上调用 .Dispose()。

public class cls1 : IDisposable
{

...

public void Dispose()
{
    _entities.Dispose();
}

将 cls1 实例放入 using 块中,如下所示:

public void GetCConfig()
{
    using(var instance = new cls1()) 
    {
      cls1.GrantAccess();
    }
}

最后,不需要下面这行,因为_entities在构造函数的开头总是空的。

if (_entities == null)
{

我建议阅读一些有关使用 C# 进行面向对象编程的基本文档,例如: https://msdn.microsoft.com/en-us/library/dd460654.aspx