Книга: C# 2008 Programmer

Static Classes

Static Classes

You can also apply the static keyword to class definitions. Consider the following FilesUtil class definition:

public class FilesUtil {
 public static string ReadFile(string Filename) {
  //---implementation---
  return "file content...";
 }
 public static void WriteFile(string Filename, string content) {
  //---implementation---
 }
}

Within this class are two static methods — ReadFile() and WriteFile(). Because this class contains only static methods, creating an instance of this class is not very useful, as Figure 4-4 shows.


Figure 4-4 

As shown in Figure 4-4, an instance of the FilesUtil class does not expose any of the static methods defined within it. Hence, if a class contains nothing except static methods and properties, you can simply declare the class as static, like this:

public static class FilesUtil {
 public static string ReadFile(string Filename) {
  //---implementation---
  return "file content...";
 }
 public static void WriteFile(string Filename, string content) {
  //---implementation---
 }
}

The following statements show how to use the static class:

//---this is not allowed for static classes---
FilesUtil f = new FilesUtil();
//---these are OK---
Console.WriteLine(FilesUtil.ReadFile(@"C:TextFile.txt"));
FilesUtil.WriteFile(@"C:TextFile.txt", "Some text content to be written");

Use static classes when the methods in a class are not associated with a particular object. You need not create an instance of the static class before you can use it.

Оглавление книги


Генерация: 2.428. Запросов К БД/Cache: 3 / 0
поделиться
Вверх Вниз