如何使用参数调用扩展方法

时间:2015-05-13 08:41:23

标签: c# select extension-methods

我有以下扩展方法:

    private RemarkItem GetRemarkItem(XElement xDataItem)
    {
        return new RemarkItem
        {
            RemarkType = RemarkType.Type1,
            Description = "bla bla" // temp
        };
    }

    private RemarkItem GetRemarkItem(XElement xDataItem, RemarkType type)
    {
        return new RemarkItem
        {
            RemarkType = type,
            Description = "bla bla" // temp
        };
    }

我知道如何使用单个参数调用该方法:

IEnumerable<RemarkItem> remarkItems = xDoc.XPathSelectElements(
                        "./Root/Remarks/Remark").Select(GetRemarkItem);

但我不知道如何使用2个参数调用该方法...

任何帮助将不胜感激

2 个答案:

答案 0 :(得分:2)

将“扩展方法”部分放在一边,将您的选择调用更改为$connection = new mysqli( "localhost", "rootaaa", "", "mysql" ); echo $connection->connect_errno;

x=>GetRemarkItem(x)

答案 1 :(得分:0)

首先,您应该创建扩展方法的正确实现:

public static class Extensions
{
    public static RemarkItem GetRemarkItem(this XElement xDataItem)
    {
        return new RemarkItem
        {
            RemarkType = RemarkType.Type1,
            Description = "bla bla" // temp
        };
    }

    public static RemarkItem GetRemarkItem(this XElement xDataItem, RemarkType type)
    {
        return new RemarkItem
        {
            RemarkType = type,
            Description = "bla bla" // temp
        };
    }
}

然后你可以这样使用它们:

IEnumerable<RemarkItem> remarkItems = xDoc.XPathSelectElements(
                    "./Root/Remarks/Remark").Select(GetRemarkItem);

    IEnumerable<RemarkItem> remarkItems = xDoc.XPathSelectElements(
                    "./Root/Remarks/Remark").Select(n => n.GetRemarkItem());

IEnumerable<RemarkItem> remarkItems = xDoc.XPathSelectElements(
                    "./Root/Remarks/Remark").Select(n => n.GetRemarkItem(RemarkType.Type1));

如果您想了解有关扩展程序的详情,请访问以下链接:https://msdn.microsoft.com/en-us//library/bb383977.aspx