c# - 我可以使用关键字 "in"以某种方式分隔方法声明中的参数吗?

标签 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# 似乎不支持定义关键字。

最佳答案

如评论中所述,您不能在 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);

关于c# - 我可以使用关键字 "in"以某种方式分隔方法声明中的参数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34820896/

相关文章:

c# Linq 关键字?

java - 如何实现特定于对象的方法?

exception - 现有方法的消息无法理解

c# - 输出未正确写入 CSV

c# - .NET 2.0 的 WCF

c# - 单击按钮在资源文件(.resx)中添加数据

c# - 无需数据库即可生成唯一编号

java - Android部分字符串关键字匹配

mysql - 如何在 MySQL 中实现对特定单词的关键字搜索?

java - 了解枚举器的枚举集