C# 字段初始值设定项无法引用非静态字段方法或属性错误
我正在尝试使用.NETC#和Azure blob存储 为了访问blob表,我遵循Microsoft的文档C# 字段初始值设定项无法引用非静态字段方法或属性错误,c#,asp.net,azure,azure-storage-blobs,C#,Asp.net,Azure,Azure Storage Blobs,我正在尝试使用.NETC#和Azure blob存储 为了访问blob表,我遵循Microsoft的文档 using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Table; using System.Threading.Tasks; using System; using System.Collections.Generic; using System.Linq; using System.Threa
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;
using System.Threading.Tasks;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WebApplication1.Controllers
{
public class EmailAdress
{
CloudStorageAccount storageAccount = new CloudStorageAccount(
new Microsoft.WindowsAzure.Storage.Auth.StorageCredentials(
"experimentstables", "token"), true);
// Create the table client.
CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
// Get a reference to a table named "peopleTable"
CloudTable pexperimentsEmailAddresses = tableClient.GetTableReference("experimentsEmailAddresses");
}
}
在这一行
CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
storageAccount标记为红色,出现以下错误:
字段初始值设定项不能引用非静态字段方法或属性
如何修复它?您声明
storageAccount
和tableClient
为类成员,因此storageAccount
必须是静态的
,才能使用它
public class EmailAdress
{
static CloudStorageAccount storageAccount = new CloudStorageAccount(...);
CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
}
或者您可以将初始化放在方法中。创建一个构造函数并在其中实现所有字段初始化
public class EmailAdress
{
CloudStorageAccount storageAccount;
CloudTableClient tableClient;
CloudTable pexperimentsEmailAddresses;
public EmailAdress()
{
storageAccount = new CloudStorageAccount(
new Microsoft.WindowsAzure.Storage.Auth.StorageCredentials(
"experimentstables", "token"), true);
// Create the table client.
tableClient = storageAccount.CreateCloudTableClient();
// Get a reference to a table named "peopleTable"
pexperimentsEmailAddresses = tableClient.GetTableReference("experimentsEmailAddresses");
}
}
报告明确指出:
实例字段的变量初始值设定项不能引用正在创建的实例。因此,在变量初始值设定项中引用它是一个编译时错误,因为变量初始值设定项通过简单的_名称引用任何实例成员是一个编译时错误
只能在构造函数中相对于另一个字段初始化字段
不会编译:
class A
{
int x = 1;
int y = x + 1; // Error, reference to instance member of this
}
class A
{
public A()
{
int x = 1;
int y = x + 1; // Works just fine
}
}
将编译:
class A
{
int x = 1;
int y = x + 1; // Error, reference to instance member of this
}
class A
{
public A()
{
int x = 1;
int y = x + 1; // Works just fine
}
}
为什么要在类内编写代码?制作一些方法或构造函数并在那里编写代码。