通用方法和谓词的问题[英] Problems with generic methods and predicates

本文是小编为大家收集整理的关于通用方法和谓词的问题的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我目前有这个通用方法:

    public virtual T Get(Expression<Func<T, bool>> predicate)
    {
        return this.Query.Where(predicate).FirstOrDefault();
    }

这是我如何调用该方法的示例:

ST = testTable.Get( u => u.PartitionKey == pKey & u.RowKey == rKey );

我真的不太了解泛型,我需要做的是有一种方法,将 partitionKey 和 rowKey 作为参数并执行 Get.像这样的:

ST = testTable.Get(pkey,rkey);

有没有人知道我该怎么做?

推荐答案

您需要创建一个接受这些参数的函数,并使用使用这些参数的 lambda 表达式调用第一个函数.

public T Get(pkey,rkey)
{
    return Get(u => u.PartitionKey == pKey & u.RowKey == rKey);
}

如果 T 不受限制继承具有这些属性的类型,则您需要创建一个扩展方法,使用具有这些属性的类型参数扩展您的类.

本文地址:https://www.itbaoku.cn/post/1556866.html

问题描述

I currently have this generic method:

    public virtual T Get(Expression<Func<T, bool>> predicate)
    {
        return this.Query.Where(predicate).FirstOrDefault();
    }

Here's an example of how I call the method:

ST = testTable.Get( u => u.PartitionKey == pKey & u.RowKey == rKey );

I really don't understand much about generics and what I need to do is to have one method that takes the partitionKey and rowKey as arguments and performs a Get. Something like this:

ST = testTable.Get(pkey,rkey);

Is there anyone out there who knows how I could do this?

推荐答案

You need to make a function that takes those parameters and calls the first function with a lambda expression that uses the parameters.

public T Get(pkey,rkey)
{
    return Get(u => u.PartitionKey == pKey & u.RowKey == rKey);
}

If T isn't constrained to inherit a type with those properties, you would need to create an extension method that extends your class with a type parameter that has those properties.