a field initializer cannot reference the nonstatic

2019-09-20 01:41发布

问题:

I am trying to work with .Net C# and Azure blob storage

I follow Microsoft's documentation in order to access a blob table.

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

in this line

CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

storageAccount is marked red with the following error:

a field initializer cannot reference the nonstatic field method or property

How should I fix it?

回答1:

Create a constructor and implement all your field initializations there.

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


回答2:

You declared storageAccount and tableClient as class members, so storageAccount has to be static in order to use it

public class EmailAdress
{
    static CloudStorageAccount storageAccount = new CloudStorageAccount(...);
    CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
}

Or you can put the initialization inside method.



回答3:

The c# language specification clearly states:

A variable initializer for an instance field cannot reference the instance being created. Thus, it is a compile-time error to reference this in a variable initializer, as it is a compile-time error for a variable initializer to reference any instance member through a simple_name.

You can initialize a field with respect to another field only in a constructor.

Will not compile:

class A
{
    int x = 1;
    int y = x + 1;        // Error, reference to instance member of this
}

Will compile:

class A
{
    public A() 
    {
        int x = 1;
        int y = x + 1;        // Works just fine
    }
}