0

我正在尝试创建包含客户联系信息和地址信息的类。

我目前正在尝试重载方法,以期压缩我的代码并使其更易于阅读,同时执行与各种方法相同的操作。另外,我正在使用 NUnit,因为这些是我正在创建的集成测试,所以这就是随机生成器的来源。这是我到目前为止所拥有的:

  public static Address BuildAddress()
    {
        var gen = new RandomGenerator();
        return BuildAddress(gen.Phrase(10));
    }

    //build a billing address
    public static AddressInfo BuildAddress(string name)
    {
        return BuildAddress(name, "USA");
    }

    public static Address BuildAddress(string name, string country)
    {
        var gen = new RandomGenerator();

        var address = Builder<AddressInfo>.CreateNew()
            .With(x => x.Name = name)
            .And((x => x.Address1 = gen.Int() + " " + gen.Phrase(10) + " Street"))
            .And(x => x.City = gen.Phrase(15))
            .And(x => x.StateOrProvince = gen.Phrase(2))
            .And(x => x.Country = country)
            .And(x => x.PostalCode = "32561").
            Build();

        return address;

我做了这个,但我也在想我需要为邮寄地址添加另一个代码块。如果有更短的方法可以做到这一点,请告诉我。

谢谢!

4

2 回答 2

4

如果我理解正确,您想缩短上面的代码,即您拥有的方法重载链......您可以使用默认属性,即:

public static Address BuildAddress(string name, int phrase = 10, string country = "USA")
{
        var gen = new RandomGenerator();

        var address = Builder<AddressInfo>.CreateNew()
            .With(x => x.Name = name)
            .And((x => x.Address1 = gen.Int() + " " + gen.Phrase(10) + " Street"))
            .And(x => x.City = gen.Phrase(15))
            .And(x => x.StateOrProvince = gen.Phrase(2))
            .And(x => x.Country = country)
            .And(x => x.PostalCode = "32561").
            Build();

        return address;
}

然后你可以这样称呼它..

ClassName.BuilderAddress("my name");

或者..

ClassName.BuilderAddress("my name", 5);

或者..

ClassName.BuilderAddress("my name", 7, "Ireland");

对您的评论的建议答案如下:(对此不是 100% 确定)

public static T BuildAddress(string name, int phrase = 10, string country = "USA")
{
        var gen = new RandomGenerator();

        var address = Builder<T>.CreateNew()
            .With(x => x.Name = name)
            .And((x => x.Address1 = gen.Int() + " " + gen.Phrase(10) + " Street"))
            .And(x => x.City = gen.Phrase(15))
            .And(x => x.StateOrProvince = gen.Phrase(2))
            .And(x => x.Country = country)
            .And(x => x.PostalCode = "32561").
            Build();

        return address;
}
于 2013-03-21T14:16:49.677 回答
0

您可能需要考虑可选参数和命名参数。

http://msdn.microsoft.com/en-us/library/dd264739.aspx

于 2013-03-21T14:14:22.517 回答