c#中的泛型和谓词
本文关键字:谓词 泛型 | 更新日期: 2023-09-27 18:02:46
我有以下不工作的代码。说明无法解析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函数的示例:
SubTest = testTable.Get(u => u.PartitionKey == "XX" & u.RowKey == "YY")
我想要的是能够像这样命名它:
SubTest = testTable.Get("XX","YY")
如果这是你的确切代码,你不能有自由浮动的函数,你需要把你的Get<T>
放在一个类中,一个最好有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();
}
}
}
这将返回某种集合,可能是IQueryable
:
this.Query.Where(u => u.PartitionKey == pkey && u.RowKey == rkey);
您的方法声称返回类型为T
的值,在这种情况下被约束为BaseTable
(或可能是一个子类)。这两种类型不兼容
@ blind是正确的,但是还有一个问题…是否T或类型返回由context.CreateQuery<T>(TableName).AsTableServiceQuery();
实际上继承从BaseTable?
class OneOfYourTables : BaseTable
{
}