错误 CS8803:顶层语句必须在命名空间和类型声明之前。

huangapple go评论122阅读模式
英文:

error CS8803: Top-level statements must precede namespace and type declarations

问题

以下是已翻译的代码部分:

// See https://aka.ms/new-console-template for more information
using Microsoft.Azure.Cosmos;
using Azure.Identity;

// 创建 CosmosClient 类的新实例
using CosmosClient client = new(
    accountEndpoint: Environment.GetEnvironmentVariable("COSMOS_ENDPOINT"),
    tokenCredential: new DefaultAzureCredential()
);

// 代表容器中的项的 C# 记录
public record Product(
    string id,
    string categoryId,
    string categoryName,
    string name,
    int quantity,
    bool sale
);

// 如果尚不存在,则创建数据库引用
Database database = client.GetDatabase(id: "cosmicworks");

Console.WriteLine("Hello, World!");

Console.WriteLine($"New database:\t{database.Id}");

// 如果尚不存在,则创建容器引用
Container container = database.GetContainer(id: "products");

Console.WriteLine($"New container:\t{container.Id}");

// 创建新对象并 upsert(创建或替换)到容器
Product newItem = new(
    id: "70b63682-b93a-4c77-aad2-65501347265f",
    categoryId: "61dba35b-4f02-45c5-b648-c6badc0cbd79",
    categoryName: "gear-surf-surfboards",
    name: "Yamba Surfboard",
    quantity: 12,
    sale: false
);

Product createdItem = await container.CreateItemAsync<Product>(
    item: newItem
);

Console.WriteLine($"Created item:\t{createdItem.id}\t[{createdItem.categoryName}]");

// 使用 ID 和分区键从容器中读取项
Product readItem = await container.ReadItemAsync<Product>(
    id: "70b63682-b93a-4c77-aad2-65501347265f",
    partitionKey: new PartitionKey("61dba35b-4f02-45c5-b648-c6badc0cbd79")
);

// 使用 SQL 字符串和参数创建查询
var query = new QueryDefinition(
    query: "SELECT * FROM products p WHERE p.categoryId = @categoryId"
)
    .WithParameter("@categoryId", "61dba35b-4f02-45c5-b648-c6badc0cbd79");

using FeedIterator<Product> feed = container.GetItemQueryIterator<Product>(
    queryDefinition: query
);

while (feed.HasMoreResults)
{
    FeedResponse<Product> response = await feed.ReadNextAsync();
    foreach (Product item in response)
    {
        Console.WriteLine($"Found item:\t{item.name}");
    }
}

希望这可以帮助您正确组织代码。如果您有任何其他问题,请随时提出。

英文:

I don't know how to write c# code. I am trying to run a sample code here - https://learn.microsoft.com/en-us/azure/cosmos-db/nosql/quickstart-dotnet?tabs=azure-portal%2Cwindows%2Cpasswordless%2Csign-in-azure-cli#create-account

This is the code I have copied in powershell. When I do dotnet run, I get error

/home/manu/Program.cs(24,1): error CS8803: Top-level statements must precede namespace and type declarations. [/home/manu/manu.csproj]

The build failed. Fix the build errors and run again.

Code

// See https://aka.ms/new-console-template for more information
using Microsoft.Azure.Cosmos;
using Azure.Identity;

// New instance of CosmosClient class
using CosmosClient client = new(
    accountEndpoint: Environment.GetEnvironmentVariable(&quot;COSMOS_ENDPOINT&quot;),
    tokenCredential: new DefaultAzureCredential()
);


// C# record representing an item in the container
public record Product(
    string id,
    string categoryId,
    string categoryName,
    string name,
    int quantity,
    bool sale
);


// Database reference with creation if it does not already exist
Database database = client.GetDatabase(id: &quot;cosmicworks&quot;);

Console.WriteLine(&quot;Hello, World!&quot;);

Console.WriteLine($&quot;New database:\t{database.Id}&quot;);


// Container reference with creation if it does not alredy exist
Container container = database.GetContainer(id: &quot;products&quot;);

Console.WriteLine($&quot;New container:\t{container.Id}&quot;);


// Create new object and upsert (create or replace) to container
Product newItem = new(
    id: &quot;70b63682-b93a-4c77-aad2-65501347265f&quot;,
    categoryId: &quot;61dba35b-4f02-45c5-b648-c6badc0cbd79&quot;,
    categoryName: &quot;gear-surf-surfboards&quot;,
    name: &quot;Yamba Surfboard&quot;,
    quantity: 12,
    sale: false
);

Product createdItem = await container.CreateItemAsync&lt;Product&gt;(
    item: newItem
);

Console.WriteLine($&quot;Created item:\t{createdItem.id}\t[{createdItem.categoryName}]&quot;);

// Point read item from container using the id and partitionKey
Product readItem = await container.ReadItemAsync&lt;Product&gt;(
    id: &quot;70b63682-b93a-4c77-aad2-65501347265f&quot;,
    partitionKey: new PartitionKey(&quot;61dba35b-4f02-45c5-b648-c6badc0cbd79&quot;)
);

// Create query using a SQL string and parameters
var query = new QueryDefinition(
    query: &quot;SELECT * FROM products p WHERE p.categoryId = @categoryId&quot;
)
    .WithParameter(&quot;@categoryId&quot;, &quot;61dba35b-4f02-45c5-b648-c6badc0cbd79&quot;);

using FeedIterator&lt;Product&gt; feed = container.GetItemQueryIterator&lt;Product&gt;(
    queryDefinition: query
);

while (feed.HasMoreResults)
{
    FeedResponse&lt;Product&gt; response = await feed.ReadNextAsync();
    foreach (Product item in response)
    {
        Console.WriteLine($&quot;Found item:\t{item.name}&quot;);
    }
}

What is the right way to structure the code?

答案1

得分: 5

你当前的代码结构是:

  • using 指令
  • 顶层语句(声明 client 变量)
  • 记录类型声明
  • 更多的顶层语句

正如错误消息所说,所有的顶层语句必须在任何类型声明之前。

修复的两个选项:

  • 停止使用顶层语句:创建一个带有 Main 方法的 Program 类,将代码放入其中,并单独声明 Product 记录。
  • 只需将 Product 记录移动到所有顶层语句之下,或移到不同的文件中。
英文:

Your current code structure is:

  • using directives
  • A top-level statement (declaring the client variable)
  • A record type declaration
  • More top-level statements

As the error message says, all top-level statements must come before any type declarations.

Two options to fix this:

  • Stop using top-level statements: create a Program class with a Main method and put your code in that, and declare the Product record separately
  • Just move the Product record to below all your top-level statements, or into a different file

huangapple
  • 本文由 发表于 2023年2月27日 16:15:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/75578108.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定