Запись моего первого DSL в C# и получение одержимого func <T> и Действие

Я предполагаю, что "myStr" является объектом Строки типа, в этом случае, это не regex. \r и \n являются эквивалентами для CR и LF.

Мое лучшее предположение то, что, если Вы знаете, что у Вас есть \n для КАЖДОЙ строки, неважно, что, тогда сначала необходимо разделить каждый \r. Тогда замените весь \n \r\n.

ответ chakrit дает, также пошел бы, но тогда необходимо использовать regex, но так как Вы не говорите, каков "myStr"...

Edit:looking в других примерах говорит мне одну вещь.. почему делают трудные вещи, когда можно сделать это легкий?, поскольку существует regex, не то же, поскольку "должен использовать": D

Edit2: инструмент очень ценен при игре с regex, xpath, и этажерка, которая дает Вам странные результаты, может я указывать на Вас на: http://www.regexbuddy.com/

6
задан sam 25 November 2009 в 06:00
поделиться

3 ответа

Итак, я понял, как написать свой DSL с помощью дополнительного построителя выражений. Вот как я хотел, чтобы мой DSL читался:

var myPreferredCoffeeFromStarbucks =
            Coffee.Make.WithCream().PourIn(
                x =>
                    {
                        x.ShotOfExpresso().AtTemperature(100);
                        x.ShotOfExpresso().AtTemperature(100).OfPremiumType();
                    }
                ).ACupSizeInOunces(16);

Вот мой проходной тест:

[TestFixture]
public class CoffeeTests
{
    [Test]
    public void Can_Create_A_Caramel_Macchiato()
    {
        var myPreferredCoffeeFromStarbucks =
            Coffee.Make.WithCream().PourIn(
                x =>
                    {
                        x.ShotOfExpresso().AtTemperature(100);
                        x.ShotOfExpresso().AtTemperature(100).OfPremiumType();
                    }
                ).ACupSizeInOunces(16);

        Assert.IsTrue(myPreferredCoffeeFromStarbucks.expressoExpressions[0].ExpressoShots.Count == 2);
        Assert.IsTrue(myPreferredCoffeeFromStarbucks.expressoExpressions[0].ExpressoShots.Dequeue().IsOfPremiumType == true);
        Assert.IsTrue(myPreferredCoffeeFromStarbucks.expressoExpressions[0].ExpressoShots.Dequeue().IsOfPremiumType == false);
        Assert.IsTrue(myPreferredCoffeeFromStarbucks.CupSizeInOunces.Equals(16));
    }
}

А вот мой DSL-класс CoffeeExpressionBuilder:

public class Coffee
{
    public List<ExpressoExpressionBuilder> expressoExpressions { get; private set; }

    public bool HasCream { get; private set; }
    public int CupSizeInOunces { get; private set; }

    public static Coffee Make
    {
        get
        {
            var coffee = new Coffee
                             {
                                 expressoExpressions = new List<ExpressoExpressionBuilder>()
                             };

            return coffee;
        }
    }

    public Coffee WithCream()
    {
        HasCream = true;
        return this;
    }

    public Coffee ACupSizeInOunces(int ounces)
    {
        CupSizeInOunces = ounces;

        return this;
    }

    public Coffee PourIn(Action<ExpressoExpressionBuilder> action)
    {
        var expression = new ExpressoExpressionBuilder();
        action.Invoke(expression);
        expressoExpressions.Add(expression);

        return this;
    }

    }

public class ExpressoExpressionBuilder
{
    public readonly Queue<ExpressoExpression> ExpressoShots = 
        new Queue<ExpressoExpression>();

    public ExpressoExpressionBuilder ShotOfExpresso()
    {
        var shot = new ExpressoExpression();
        ExpressoShots.Enqueue(shot);

        return this;
    }

    public ExpressoExpressionBuilder AtTemperature(int temp)
    {
        var recentlyAddedShot = ExpressoShots.Peek();
        recentlyAddedShot.Temperature = temp;

        return this;
    }

    public ExpressoExpressionBuilder OfPremiumType()
    {
        var recentlyAddedShot = ExpressoShots.Peek();
        recentlyAddedShot.IsOfPremiumType = true;

        return this;
    }
}

public class ExpressoExpression
{
    public int Temperature { get; set; }
    public bool IsOfPremiumType { get; set; }

    public ExpressoExpression()
    {
        Temperature = 0;
        IsOfPremiumType = false;
    }
}

Любые предложения приветствуются.

3
ответ дан 17 December 2019 в 02:30
поделиться

Что, если .IncludeApps примет массив AppRegistrations

IncludeApps(params IAppRegistration[] apps)

, затем

public static class App
{
  public static IAppRegistration IncludeAppFor(AppType type)
  {
    return new AppRegistration(type);
  }
}

public class AppRegistration
{
  private AppType _type;
  private bool _cost;

  public AppRegistration(AppType type)
  {
    _type = type;
  }

  public AppRegistration AtNoCost()
  { 
    _cost = 0;
    return this;
  }
}

, так что в конечном итоге это будет выглядеть так ...

.IncludeApps
(
  App.IncludeAppFor(AppType.Any), 
  App.IncludeAppFor(AppType.Any).AtNoCost()
)

Внутри вашего метода IncludeApps вы должны проверить регистрации и создать объекты по мере необходимости.

2
ответ дан 17 December 2019 в 02:30
поделиться

Может быть, для перехода по маршруту делегата что-то вроде этого сработает?

var aPhone = MyPhone.Create;
  MyPhone.Create.IncludeApps
  (
    x =>
      {
        x.IncludeAppFor(new object());
      }
  );

class MyPhone
  {
    public MyPhone IncludeApps(Action<MyPhone> includeCommand)
    {
        includeCommand.Invoke(this);
        return this;
    }
  }

Если вы не настроены на маршрут делегата, возможно, параметры будут работать?

var anotherPhone = MyPhone.Create.IncludeApps(
    new IncludeAppClass(AppType.Math),
    new IncludeAppClass(AppType.Entertainment).AtNoCost());


class MyPhone
{
    internal MyPhone IncludeApps(params IncludeAppClass[] includeThese)
    {
        if (includeThese == null)
        {
            return this;
        }
        foreach (var item in includeThese)
        {
            this.Apps.Add(Item);
        }
        return this;
    }
}
1
ответ дан 17 December 2019 в 02:30
поделиться
Другие вопросы по тегам:

Похожие вопросы: