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

标签 c#-4.0 static

我已经创建了类名 cls1 并创建了名为 GrantAccess() 的方法。但是我无法访问 _entities。它显示以下错误 “错误 1 ​​非静态字段、方法或属性‘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");
        }
    }
}  

上述方法在其他类中调用。

 public void GetCConfig()
 {
 cls1.GrantAccess();
 }

最佳答案

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");
    }
}

关于c#-4.0 - 非静态字段、方法或属性需要对象引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29890273/

相关文章:

android - 在应用程序类中绑定(bind) Android 服务是个好主意吗?

c# - 连接对象数组中的唯一字符串

具有未定义行为的 C++ 代码,编译器生成 std​​::exception

iphone - 如何在 iPhone/XCode 中定义静态字符串表?

c# - 区分 FileSystemWatcher 中的 Changed 和 Created 事件?

html - 静态文件未加载 [DJANGO]

c++ - 之间的差异。和::在 C++ 中用于静态成员?

C# 2010 : Deploying Multiple Apps. 。需要 Sure Fire 方式来更新

c# - datagridview单元格鼠标悬停背景色更改

c# - 如何洗牌多个相关数组?