我可以使用关键字“in”以某种方式分离方法声明中的参数吗?

时间:2016-01-15 22:23:52

标签: c# keyword method-declaration

我想创建一个方法,该方法使用关键字in而不是逗号来分隔方法声明中的参数;与foreach(a in b)方法类似的东西。

示例

班级结构

public class Length
{
    public double Inches;
    public double Feet;
    public double Yards;

    public enum Unit { Inch, Foot, Yard }

    Dictionary<Unit, double> inchFactor = new Dictionary<Unit, double>()
    {
        { Unit.Inch, 1 },
        { Unit.Foot, 12 },
        { Unit.Yard, 36 }
    };

    public Length(double value, Unit unit)
    {
        this.Inches = value * inchFactor[unit];
        this.Feet = this.Inches / inchFactor[Unit.Foot];
        this.Yards = this.Inches / inchFactor[Unit.Yard];
    }
}

中的方法定义
// I'd like to know how to use "in" like this  ↓
public List<Length> MultiplesOf(Length divisor in Length dividend)
{
    double inchEnumeration = divisor.Inches;
    List<Length> multiples = new List<Length>();

    while (inchEnumeration <= dividend.Inches)
    {
        multiples.Add(new Length(inchEnumeration, Length.Unit.Inch));
        inchEnumeration += divisor.Inches;
    }

    return multiples;
}

理想实施

private void DrawRuler()
{
    Length eighthInch = new Length(0.125, Length.Unit.Inch);
    Length oneFoot = new Length(1, Length.Unit.Foot);

    // Awesome.
    List<Length> tickGroup = Length.MultiplesOf(eighthInch in oneFoot);

    double inchPixels = 10;
    foreach (Length tick in tickGroup)
    {
        // Draw ruler.
    }
}

我考虑过创建新的关键字,但看起来C#不支持定义关键字。

2 个答案:

答案 0 :(得分:2)

正如评论中所提到的,您无法在C#中定义自定义关键字(除非您扩展编译器,这是一项高级任务)。但是,如果您的目标是澄清两个论点的含义,那么我建议改为使用named arguments

// Define the method as usual:
public List<Length> MultiplesOf(Length divisor, Length dividend)
{
    // ...
}

// Then call it like so, explicitly showing what is the divisor and the dividend:  
List<Length> tickGroup = Length.MultiplesOf(divisor: eighthInch, dividend: oneFoot);

答案 1 :(得分:1)

虽然您无法重新定义现有关键字,但还有其他方法可以使用Fluent界面以稍微不同的方式完成您的操作:

public class Length
{
    // ...

    public static IFluentSyntaxProvider MultiplesOf(Length divisor)
    {
        return new FluentSyntaxProvider(divisor);
    }

    public interface IFluentSyntaxProvider
    {
        List<Length> In(Length dividend);
    }
    private class FluentSyntaxProvider : IFluentSyntaxProvider
    {
        private Length divisor;

        public FluentSyntaxProvider(Length divisor)
        {
            this.divisor = divisor;
        }

        public List<Length> In(Length dividend)
        {
            double inchEnumeration = divisor.Inches;
            List<Length> multiples = new List<Length>();

            while (inchEnumeration <= dividend.Inches)
            {
                multiples.Add(new Length(inchEnumeration, Length.Unit.Inch));
                inchEnumeration += divisor.Inches;
            }

            return multiples;
        }
    }
}

使用示例:

// Awesome.
List<Length> tickGroup = Length.MultiplesOf(eighthInch).In(oneFoot);