Книга: 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.
- Classes
- Using Partial Classes
- Container classes
- КЛЮЧЕВЫЕ СЛОВА: auto, extern, static, register
- 16.2.3. Static Kernel Command Line
- 3.1.10 Static Variables
- 4.1.6 Static Function Variables
- Static IPX Routing Using the ipx_route Command
- Configuring a static IP addresses
- Chapter 4 Classes and Objects
- Sealed Classes and Methods
- Generic Classes