我正在AppDelegate.cs中创建某个实例(数据库类),并希望从我的ViewControllers访问此实例。它返回一个CS0120错误,“访问非静态成员`GeomExample.AppDelegate._db'(CS0120)需要一个对象引用”
我在AppDelegate中创建我的实例,如下所示:
[Register ("AppDelegate")]
public partial class AppDelegate : UIApplicationDelegate
{
...
public Database _db;
public override bool FinishedLaunching (UIApplication app, NSDictionary options)
{
...
_db = new Database (Path.Combine (Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments), "myDb.db"));
_db.Trace = true;
然后我尝试像这样访问它,这会产生错误:
IEnumerable<DbShapeElement> shapes = AppDelegate._db.GetShapeElements (_shapeName, null);
任何帮助表示赞赏!
答案 0 :(得分:4)
警告:我不知道MonoTouch,但是读到这个问题:Monotouch: How to update a textfield in AppDelegate partial class?。
在我看来:
public Database _db;
非静态。您需要使用您拥有的AppDelegate实例。
试试这个:
var ad = (AppDelegate) UIApplication.SharedApplication.Delegate;
IEnumerable<DbShapeElement> shapes = ad._db.GetShapeElements (_shapeName, null);
修改强>
使用具有私有setter的属性来阻止在AppDelegate类之外进行修改,而不是使用公共实例变量,更清晰:
[Register ("AppDelegate")]
public partial class AppDelegate : UIApplicationDelegate
{
...
public Database Db {
get;
private set;
}
public override bool FinishedLaunching (UIApplication app, NSDictionary options)
{
...
Db = new Database (Path.Combine (Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments), "myDb.db"));
Db.Trace = true;
...
然后你在AppDelegate类之外像这样访问它:
var ad = (AppDelegate) UIApplication.SharedApplication.Delegate;
IEnumerable<DbShapeElement> shapes = ad.Db.GetShapeElements (_shapeName, null);