如何在 c# 中构建通用方法来查询给定 Azure Table 中的分区
How can I Build a Generic Method in c# to Query a Partition in a Given Azure Table
我正在尝试为给定 Azure table 的分区中的 return 条目构建通用方法。这是它的样子:
public class Table : ITable
{
private CloudStorageAccount storageAccount;
public Table()
{
var storageAccountSettings = ConfigurationManager.ConnectionStrings["AzureWebJobsStorage"].ToString();
storageAccount = CloudStorageAccount.Parse(storageAccountSettings);
}
public async Task<IEnumerable<T>> RetrieveAllInPartition<T>(string tableReference, string partitionKey) where T : ITableEntity
{
var tableClient = storageAccount.CreateCloudTableClient();
var table = tableClient.GetTableReference(tableReference);
var query = new TableQuery<T>().Where(TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, partitionKey));
var results = await table.ExecuteQuerySegmentedAsync<T>(query,null);
return results;
}
}
这没有编译我得到:
CS0310 'T' must be a non-abstract type with a public parameterless
constructor in order to use it as parameter 'TElement' in the generic
type or method
'CloudTable.ExecuteQuerySegmentedAsync(TableQuery,
TableContinuationToken)'
有什么解决方法吗?
您需要向通用参数添加 new()
约束:
public async Task<IEnumerable<T>> RetrieveAllInPartition<T>(string tableReference, string partitionKey)
where T : ITableEntity, new()
因为ExecuteQuerySegmentedAsync
也有这个约束(在documentation中可以看出)。
此约束是 ExecuteQuerySegmentedAsync
所必需的,否则它将无法为您创建 T
的实例。请参阅 documentation 以了解有关 new()
约束的更多信息。
我正在尝试为给定 Azure table 的分区中的 return 条目构建通用方法。这是它的样子:
public class Table : ITable
{
private CloudStorageAccount storageAccount;
public Table()
{
var storageAccountSettings = ConfigurationManager.ConnectionStrings["AzureWebJobsStorage"].ToString();
storageAccount = CloudStorageAccount.Parse(storageAccountSettings);
}
public async Task<IEnumerable<T>> RetrieveAllInPartition<T>(string tableReference, string partitionKey) where T : ITableEntity
{
var tableClient = storageAccount.CreateCloudTableClient();
var table = tableClient.GetTableReference(tableReference);
var query = new TableQuery<T>().Where(TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, partitionKey));
var results = await table.ExecuteQuerySegmentedAsync<T>(query,null);
return results;
}
}
这没有编译我得到:
CS0310 'T' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'TElement' in the generic type or method
'CloudTable.ExecuteQuerySegmentedAsync(TableQuery, TableContinuationToken)'
有什么解决方法吗?
您需要向通用参数添加 new()
约束:
public async Task<IEnumerable<T>> RetrieveAllInPartition<T>(string tableReference, string partitionKey)
where T : ITableEntity, new()
因为ExecuteQuerySegmentedAsync
也有这个约束(在documentation中可以看出)。
此约束是 ExecuteQuerySegmentedAsync
所必需的,否则它将无法为您创建 T
的实例。请参阅 documentation 以了解有关 new()
约束的更多信息。