扩展函数以接受列表 - C# [英] Extend a function to accept a list - C#

查看:60
本文介绍了扩展函数以接受列表 - C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下接受字符串数组或数组对象的函数。我想扩展这个函数,它也接受一个对象列表和一个字符串列表。



找不到如何实现它的方法。任何帮助将不胜感激。



I have the following function that accepts an array of strings or an array object. I want to extend this function in such a way that it also accepts a list of objects and a list of strings.

Cannot find a way of how to implement it. Any help would be appreciated.

public override void Run()
        {
            log.Trace(this, String.Format(LoggingConstants.StartCustomStep, this.GetType().Name));

            object[] realList;
            object rawList = (object)GetInput("List", typeof(object));
            object item = (object)GetInput("Item", typeof(object));

            if (rawList is object[])
            {
                realList = (object[])rawList;
            }
            else if (rawList is string)
            {
                realList = (rawList as string).Split(";".ToCharArray());
            }
            else
                throw new ArgumentException("Invalid List argument supplied.  Must be an array or string.");

            string status = StatusConstants.Fail;;
            if (item != null)
            {
                foreach (object listItem in realList)
                {
                    if (item.Equals(listItem))
                    {
                        status = StatusConstants.Pass;
                        break;
                    }
                }
            }

            SetOutput("Status", status);

            log.Trace(this, String.Format(LoggingConstants.EndCustomStep, this.GetType().Name));
        }





我的尝试:



什么都没有成功。然而有人建议首先检查列表,然后使用else if检查数组



What I have tried:

nothing that managed to work. However someone advised to start by checking the list then use else if to check the array

推荐答案

让方法接受 IEnumerable< string>< ; / string> 参数。列表和数组都实现IEnumerable,您仍然可以使用 foreach 遍历成员。
Have the method accept an IEnumerable<string></string> argument. Both lists and arrays implement IEnumerable, and you can still iterate through the members with foreach.


这篇关于扩展函数以接受列表 - C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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