在c#中创建重载方法

时间:2013-03-21 14:11:05

标签: c# nunit overloading

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

我目前正在尝试重载方法,希望在执行与各种方法相同的操作时缩小代码并使其更易于阅读。此外,我正在使用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;

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

谢谢!

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:0)

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

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