我正在使用 Windows Azure 移动服务创建一个 Windows Phone 8 应用程序 (c#) 来存储我的数据。我从azure下载的示例如下:
public class TodoItem
{
public string Id { get; set; }
[JsonProperty(PropertyName = "text")]
public string Text { get; set; }
[JsonProperty(PropertyName = "complete")]
public bool Complete { get; set; }
}
public class FVItemData
{
private MobileServiceCollection<Entity.FV_Person, Entity.FV_Person> items;
private IMobileServiceTable<Entity.FV_Person> FVTable = App.MobileService.GetTable<Entity.FV_Person>();
public async void InsertTodoItem(Entity.FV_Person fvItem)
{
await FVTable.InsertAsync(fvItem);
items.Add(fvItem);
}
}
但是现在我已经创建了一个新的cs文件,名为InsertClass.cs。我想将 FVItemData 类移至 InsertClass.cs。我尝试了以下方法:
InsertClass.cs
namespace GetStartedWithData.ViewModel
{
public class FVItemData
{
private MobileServiceCollection<FV_Person, FV_Person> items;
private IMobileServiceTable<FV_Person> FVTable = App.MobileService.GetTable<FV_Person>();
private async void InsertTodoItem(FV_Person fvItem)
{
await FVTable.InsertAsync(fvItem);
items.Add(fvItem);
}
}
}
MainPage.xaml.cs
private void ButtonSave_Click(object sender, RoutedEventArgs e)
{
var FVItem = new FV_Person { Text = InputText.Text };
FVItemData.InsertPerson(FVItem); <--- I try this but error!
}
如何从MainPage.xaml.cs调用InsertClass.cs中的InsertTodoItem函数?请帮忙,我一整天都没有尝试。我是 C# 新手。谢谢...
更新:
我修改了问题,但我的错误有同一行,错误消息是“'GetStartedWithData.ViewModel.FVItemData'不包含'InsertPerson'的定义”
最佳答案
您的代码中存在一些问题:
构建问题
您正在尝试直接使用类名来访问实例方法 (FVItemData.InsertTodoItem
)。实例方法需要通过实例(即该类的对象)来访问。您可以创建 FVItemData
的实例,然后调用 InsertTodoItem
:
private void ButtonSave_Click(object sender, RoutedEventArgs e)
{
var FVItem = new FV_Person { Text = InputText.Text };
var fvItemData = new FVItemData();
fvItemData.InsertPerson(FVItem);
}
或者您可以将其设置为静态方法,您可以通过类本身访问该方法 - 请注意,您可能还需要将 FVTable
字段设置为 static
。:
public class FVItemData
{
//...
private async void InsertTodoItem(FV_Person fvItem)
{
await FVTable.InsertAsync(fvItem);
items.Add(fvItem);
}
}
运行时问题
一旦构建问题得到解决,您可能会在调用 NullReferenceException
时遇到 items.Add(fvItem)
- 由于项目未初始化,因此它将为空。您使用 MobileServiceCollection<T1,T2>
作为 items
字段的类型,但仅当您将数据绑定(bind)与某些 UI 控件一起使用时才应使用该类型 - 并且您也不应直接将项目插入到集合中。您可能需要的是一个简单的 List<FVPerson>
,它可以在您插入项目时容纳它们。
关于c# - Windows Azure 移动服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17493952/