c# - Can I use the keyword "in" to separate parameters in a method declaration somehow? -
i create method uses keyword in
instead of comma separate parameters in method declaration; similar foreach(a in b)
method.
example
class structure
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]; } }
method definition in class
// i'd know how use "in" ↓ 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; }
ideal implementation
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. } }
i've looked creating new keywords, looks c# not support defining keywords.
while can't redefine existing keyword, there other way accomplish in different way using fluent interface :
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; } } }
example of usage :
// awesome. list<length> tickgroup = length.multiplesof(eighthinch).in(onefoot);
Comments
Post a Comment