如何指定列表中选择方法? [英] How to specify a list selection method?

查看:104
本文介绍了如何指定列表中选择方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个计算列表的方法。在该算法的某些点需要被选择从列表中的单个元件。这其实并不重要选择哪一个元素,但我想离开它给用户来决定。

I've got a method that computes a list. At certain points in the algorithm a single element from the list needs to be chosen. It doesn't really matter which element is chosen, but I'd like to leave it up to the user to decide.

现在,我已经添加一个扩展方法的IList< T> .Random()它只是需要一个随机元素。 。首先()将同等效果的工作。假如我想让用户选择使用哪种方法,或者可能是完全不同的方法,怎么会看上去?

Right now, I've added an extension method IList<T>.Random() which simply takes a random element. .First() would have worked equally as well. Supposing I want to let the user pick which method is used, or perhaps an entirely different method, how would that look?

我想使用有限的选项枚举,然后我可以换每个调用一个开关,并调用相应的功能。 不过也许某种lambda函数的会比较合适

I was thinking about using an enum with limited options, and then I could wrap each of these calls in a switch and call the appropriate function. But maybe some sort of lambda function would be more appropriate?

此方法需要在两个不同的地方在列表中所使用,一次;焦炭&GT; ,一旦在列表&LT;串&GT; 。我想用两个同样的方法。

This method needs to be used in two different places, once on a List<char> and once on a List<string>. I want to use the same method for both.

这是不是一个GUI应用程序。我试图决定如何设计的API。

This isn't a GUI app. I'm trying to decide how to design the API.

具体而言,我想有一个像

Specifically, I want to have a field like

public Func<IList<T>, T> SelectElement = list => list.First();

哪些随后将在该方法中被使用,

Which would then be used in the method,

 public string Reverse(string pattern, IList<object> args = null, IDictionary<string, object> kwargs = null)

但是通用字段是不可能的。所以,我正在寻找一个替代解决方案。其中之一是使 SelectElement 方法的参数为反转(),那么我可以使它通用...但我希望能保持在一类水平可重用性。不想再ARGS传递给函数,如果我能帮助它。

But generic fields aren't possible. So I'm looking for an alternative solution. One would be to make the SelectElement method an argument to Reverse(), then I could make it generic... but I was hoping to keep it at a class-level for re-usability. Don't want to pass any more args to the function if I can help it.

编辑:全部源$ C ​​$ C

推荐答案

这个怎么样:


    public class MyClass
    {
        public static class C<T>
        {
            public static Func<IList<T>, T> SelectElement;
        }

        public int Test(IList<int> list)
        {
            return C<int>.SelectElement(list);
        }
    }

    static class Program
    {
        static void Main(string[] args)
        {
            MyClass.C<char>.SelectElement = xs => xs.First();
            MyClass.C<int>.SelectElement = xs => xs.First();

            var list = new List<int>(new int[] { 1, 2, 3 });

            var c = new MyClass();

            var v = c.Test(list);
            Console.WriteLine(v);
        }
    }

这篇关于如何指定列表中选择方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆