开发者

C# Is it possible to use an DB object reference in a static method?

public abstract class AbstractDBConnector { private AdServiceDB db;

    public AdServiceDB Adapter
    {
        get 
        {
            if (db == null) db = new 开发者_JAVA百科AdServiceDB();
            return db;
        }
    }
}

and a class that inherits from it:

public class BaseDataValidator : AbstractDBConnector
{
    public static bool Check()
    {
        var t = Adapter.Users.Where(x=>x.Id<10).ToList(); //the error is here
        return true; //example
    }
}

this code obviously generates an error: An object reference is required for the non-static field, method, or property Is it even possible to do a trick to use the Adapter in the static method ?


Only if Adapter is also static, which you probably don't want it to be (but maybe you do, I'm not sure what the exact use case is, there's not enough info). Pass the adapter to the method as a parameter if the method must be static, but it seems more likely that your method just shouldn't be static in the first place.

EDIT: note that for the "make it static approach to work you'll have to make both Adapter and db static.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜