.NET 指南:参数的设计

本文中的这个指南有助于你为成员参数选择正确的类型和名称。下列文章同样呈现了参数的设计指南。

  • 枚举与 Boolean 参数之间的选择
  • 使用可变数量的参数的成员。
  • 指针参数
  • 传递参数
  • 验证参量
使用最少被获得的并通过成员来提供必需功能的变量类型。

下列代码范例说明了这个指导方针。BookInfo 类继承自 Publication 类。Manager 类实现了两个方法:BadGetAuthorBiography 和 GoodGetAuthorBiography。BadGetAuthorBiography 使用了一个 BookInfo 对象的引用,尽管它只使用了在 Publication 里被声明的成员。GoodGetAuthorBiography 方法示范了正确的设计。

// 拥有基本信息的类。

public class Publication

{

    string author;

    DateTime publicationDate;

    

    public Publication(string author, DateTime publishDate)

    {

        this.author = author;

        this.publicationDate = publishDate;

    }

    public DateTime PublicationDate

    {

        get {return publicationDate;}

    }

    public string Author

    {

        get {return author;}

    }

}



// 继承自 Publication 的类

public class BookInfo :Publication

{

    string isbn;

    public BookInfo(string author, DateTime publishDate, string isbn) :

            base(author, publishDate)

    {

        this.isbn = isbn;

    }

    public string Isbn

    {

        get {return isbn;}

    }

}



public class Manager

{

    // 这个方法没有使用 Isbn 成员,因此它不需要 Books 的一个专门引用

    static string BadGetAuthorBiography(BookInfo book)

    {

        string biography = "";

        string author = book.Author;

        // 在这里操作。

        return biography;



    }

    // 这个方法说明了正确的设计。

    static string GoodGetAuthorBiography(Publication item)

    {

        string biography = "";

        string author = item.Author;

        // 在这里操作。

        return biography;

    }

}
不要使用被保留的参数。

库的将来版本中能够添加能够获取附加属性的新重载。

下列代码范例首先示范了一个违反了这个指导方针的错误方法,然后说明了另外一个正确被设计的方法。

    public void BadStoreTimeDifference (DateTime localDate, 

        TimeZone toWhere, 

        Object reserved)

    {

        // 在这里操作。

    }



public void GoodCStoreTimeDifference (DateTime localDate, 

    TimeZone toWhere)

{

    // 在这里操作。

}

public void GoodCStoreTimeDifference (DateTime localDate, 

    TimeZone toWhere, 

    bool useDayLightSavingsTime)

{

    // 在这里操作

}
不要公开暴露获取指针、指针的数组,或者多维数组来作为参数的方法。

在使用大部分库的时候,明白这些高级特征应该不是必须的。

把所有的输出参数放到经值传递的参数和 ref 参数(排除参数的数组)的后面,即使这样做导致了在重载之间的参数次序出现矛盾。

这个约定使方法的签名更加容易被理解。

在成员重载或实现接口成员的时候保持一致的参数命名。

重载应该使用相同的参数名称。重载应该使用与成员声明相同的参数名称。接口的实现应该使用在接口成员的签名中被定义的相同名称。

你可能感兴趣的:(.net)