[英]Generics and predicates in c#
我有以下代碼不起作用。 就是說 PartitionKey 和 RowKey 的值無法解析。 希望有高手可以給我一些建議。 到目前為止,我所擁有的都是基於一些建議,但仍然無法正常工作。
public class BaseTable
{
public string PartitionKey { get; set; }
public string RowKey { get; set; }
}
public abstract class AzureTableBase<T> : IAzureTable<T>
{
// This method gives the errors. The idea of this method is that instead of
// supplying the predicate you can just supply a value for partitionkey and
// rowkey as parameters. The problem is that it doesn't work and give the
// following syntax errors:
//
// Cannot resolve symbol PartitionKey
// Cannot resolve symbol RowKey
public virtual T Get<T>(string pkey, string rkey) where T : BaseTable
{
var a = this.Query.Where(u => u.PartitionKey == pkey && u.RowKey == rkey);
}
// Following method works:
public virtual T Get(Expression<Func<T, bool>> predicate)
{
return this.Query.Where(predicate).FirstOrDefault();
}
public virtual IQueryable<T> Query
{
get
{
TableServiceContext context = CreateContext();
return context.CreateQuery<T>(TableName).AsTableServiceQuery();
}
}
}
下面是我目前如何調用第二個 Get function 的示例:
SubTest = testTable.Get(u => u.PartitionKey == "XX" & u.RowKey == "YY")
我想要的是能夠這樣稱呼它:
SubTest = testTable.Get("XX","YY")
如果那是您的確切代碼,則不能具有自由浮動功能,則需要將Get<T>
放入 class 中,該代碼最好具有各種Query
字段。
根據您更新的帖子和您完全拒絕發布完整的代碼,我只能假設您並不真正關心(甚至理解)您的代碼做了什么,只是它可以編譯。 在那張紙條上,
public abstract class AzureTableBase<T> : IAzureTable<T> where T : BaseTable
{
// don't need to re-generalize this function, T is already inherited from your class
public virtual T Get(string pkey, string rkey)
{
var a = this.Query.Where(u => u.PartitionKey == pkey && u.RowKey == rkey);
return a.FirstOrDefault(); // again, only guessing.
}
public virtual IQueryable<T> Query
{
get
{
TableServiceContext context = CreateContext();
return context.CreateQuery<T>(TableName).AsTableServiceQuery();
}
}
}
@Blindly 是正確的,但還有另一部分...... T 或 Type 是否由context.CreateQuery<T>(TableName).AsTableServiceQuery();
返回實際上繼承自BaseTable?
例子
class OneOfYourTables : BaseTable
{
}
如果沒有,那是你的問題。
這將返回某種集合,可能是IQueryable
:
this.Query.Where(u => u.PartitionKey == pkey && u.RowKey == rkey);
您的方法聲稱返回T
類型的值,在這種情況下,它被限制為BaseTable
(或可能是子類)。 這兩種類型不兼容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.