传递 Func其中 TResult 未知

发布于 2024-10-02 05:48:48 字数 2177 浏览 2 评论 0 原文

注意:请适当地重新标记和/或重新命名


我有一个类 FooEnumerator,它包装 Foo 并实现 IEnumerable >。 Foo 表示一个树状数据结构,枚举的 FooEnumerator 是当前节点的子节点。

Foo 是供应商提供的数据对象。 FooEnumerator 实现了一堆自定义过滤代码。

class FooEnumerator : IEnumerable<FooEnumerator>
{
    public Foo WrappedNode { get; private set; }
    public string Name { get { return WrappedNode.Name; } }
    public int Id { get{ return WrappedNode.Id; } }
    public DateTime Created { get{ return WrappedNode.Created; } }

    public FooEnumerator(Foo wrappedNode)
    {
        WrappedNode = wrappedNode;
    }

    public IEnumerator<FooEnumerator> GetEnumerator()
    {
          foreach (Foo child in this.GetChildren())
              if(FilteringLogicInHere(child))
                    yield return new FooEnumerator(child);
    }

    ...
}

我希望能够使用给定的(任意)表达式对树的每个级别进行排序,该表达式是在创建顶级 FooEnumerator 时定义的,并将该表达式向下传递给每个新枚举的项目以供使用。

我想使用 lambda 定义排序表达式,就像使用 OrderBy 函数一样。事实上,我的目的是将 lambda 传递给 OrderBy

OrderBy 的签名是

OrderBy<TSource, TKey>(Func<TSource, TKey> keySelector)

其中 TKey 是给定 Func 的返回类型,但它是方法签名中的类型参数,并在编译时确定。

用法示例

var x = GetStartingNode();

var sort = n => n.DateTime;
var enu = new FooEnumerator(x, sort);

var sort2 = n => n.Name;
var enu2 = new FooEnumerator(x, sort2);

然后,排序表达式将存储在类变量中,FooEnumerator 的工作方式如下:

// pseudo-implementation

private Expression<Func<Foo, TKey>> _sortBy;

public FooEnumerator(Foo wrappedNode, Expression<Func<Foo, TKey>> sortBy)
{
    WrappedNode = wrappedNode;
    _sortBy = sortBy;
}

public IEnumerator<FooEnumerator> GetEnumerator()
{
    foreach (Foo child in this.GetChildren().OrderBy(_sortBy))
        if(FilteringLogicInHere(child))
            yield return new FooEnumerator(child);
}

在此用例中如何指定 TKey 的类型(隐式或显式)?

我不想对其进行硬编码,因为我希望能够对底层 Foo 的任何和所有属性进行排序。

Note: Please re-tag and/or re-name appropriately


I have a class, FooEnumerator, that wraps a Foo and implements IEnumerable<FooEnumerator>. The Foos represent a tree-like data structure, the FooEnumerators that are enumerated are the child nodes of the current node.

Foo is a vendor supplied data object. FooEnumerator implements a bunch of custom filtering code.

class FooEnumerator : IEnumerable<FooEnumerator>
{
    public Foo WrappedNode { get; private set; }
    public string Name { get { return WrappedNode.Name; } }
    public int Id { get{ return WrappedNode.Id; } }
    public DateTime Created { get{ return WrappedNode.Created; } }

    public FooEnumerator(Foo wrappedNode)
    {
        WrappedNode = wrappedNode;
    }

    public IEnumerator<FooEnumerator> GetEnumerator()
    {
          foreach (Foo child in this.GetChildren())
              if(FilteringLogicInHere(child))
                    yield return new FooEnumerator(child);
    }

    ...
}

I want to be able to sort each level of the tree with a given (arbitrary) expression, defined when the top level FooEnumerator is created, and have this expression passed down to each newly enumerated item to use.

I'd like to define the sort expression using lambda's, in the same way you would with the OrderBy function. In fact, it is my intention to pass the lambda to OrderBy.

The signiture for OrderBy is

OrderBy<TSource, TKey>(Func<TSource, TKey> keySelector)

where TKey is the return type of the given Func, but is a Type Parameter in the method signature and is figured out at compile time.

Example usage

var x = GetStartingNode();

var sort = n => n.DateTime;
var enu = new FooEnumerator(x, sort);

var sort2 = n => n.Name;
var enu2 = new FooEnumerator(x, sort2);

The sort expression would then be stored in a class variable and FooEnumerator would work like:

// pseudo-implementation

private Expression<Func<Foo, TKey>> _sortBy;

public FooEnumerator(Foo wrappedNode, Expression<Func<Foo, TKey>> sortBy)
{
    WrappedNode = wrappedNode;
    _sortBy = sortBy;
}

public IEnumerator<FooEnumerator> GetEnumerator()
{
    foreach (Foo child in this.GetChildren().OrderBy(_sortBy))
        if(FilteringLogicInHere(child))
            yield return new FooEnumerator(child);
}

How can I specify the type of TKey (implicitly or explicitly) in this use case?

I don't want to hard code it as I want to be able to sort on any and all properties of the underlying Foo.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

少年亿悲伤 2024-10-09 05:48:48

嗯,您无法创建 Expression> 类型的成员委托变量,因为 TKey 从未被指定。但是,您可以创建 Expression> 类型的成员,这可能足以满足您的目的。当然,您可能还需要更改 FooEnumerator 构造函数以接受此签名。

编辑:其他人建议参数化您的FooEnumerator,以便它接受TKey。您当然可以这样做,但您应该意识到出现的问题:

  1. 通过参数化枚举器,您将彻底失败。任何想要存储 FooEnumeratorFooEnumerator 的代码都将彻底失败。 T> 必须具有类型 T 的先验知识。但是,您可以实现一个非通用接口 IFooEnumerator 来处理这个问题。
  2. 如果您希望将来支持对多个字段进行排序,则参数化枚举器会产生问题。C# 不支持具有可变数量类型参数的泛型,这限制了需要多个任意类型的泛型的创建。这个问题比较难处理,因为开始创建 FooEnumeratorFooEnumeratorFooEnumerator,等等。

Well, you can't create a member delegate variable of type Expression<Func<Foo,TKey>> since TKey is never specified. However, you could create a member of type Expression<Func<Foo,IComparable>> which may suffice for your purposes. You could need to change your FooEnumerator constructor to accept this signature as well, of course.

EDIT: Others have suggested parameterizing your FooEnumerator so that it accepts a TKey. You can certainly do this, but you should be aware of the issues that emerge:

  1. By parameterizing the enumerator you are then kicking the bucket down the road. Any code that wants to store a FooEnumerator<T> has to have a-priori knowledge of the type T. You could, however, implement a non-generic interface IFooEnumerator to deal with that.
  2. Parameterizing an enumerator creates issues if you want to support ordering on multiple fields in the future. C# doesn't support generics with a variable number of type parameters, which limits the creation of generics that require multiple arbitrary types. This issue is harder to deal with, since it's awkward to start creating FooEnumerator<T>, FooEnumerator<T1,T2>, FooEnumerator<T1,T2,T3...>, and so on.
你列表最软的妹 2024-10-09 05:48:48

您还可以参数化您的枚举器:

class FooEnumerator<TKey> {

  // ... All your 'pseudo' code would work here

}

不过,我建议使用 IComparable 针对接口进行编程。

You can also parameterize your Enumerator:

class FooEnumerator<TKey> {

  // ... All your 'pseudo' code would work here

}

I recommend programming against the interface using IComparable however.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文