以下是MSDN在何时使用静态类时要说的内容:
Run Code Online (Sandbox Code Playgroud)static class CompanyInfo { public static string GetCompanyName() { return "CompanyName"; } public static string GetCompanyAddress() { return "CompanyAddress"; } //... }使用静态类作为与特定对象无关的方法的组织单位.此外,静态类可以使您的实现更简单,更快,因为您不必创建对象来调用其方法.以有意义的方式组织类中的方法很有用,例如System命名空间中Math类的方法.
对我来说,这个例子似乎并没有涵盖静态类的很多可能的使用场景.在过去,我已经将静态类用于相关函数的无状态套件,但这就是它.那么,在什么情况下应该(而且不应该)将一个类声明为静态?
我之前没有使用过很多静态方法,但最近我倾向于使用更多静态方法.例如,如果我想在类中设置一个布尔标志,或者在一个类中设置一个布尔标志而不需要通过类传递实际对象.
例如:
public class MainLoop
{
private static volatile boolean finished = false;
public void run()
{
while ( !finished )
{
// Do stuff
}
}
// Can be used to shut the application down from other classes, without having the actual object
public static void endApplication()
{
MainLoop.finished = true;
}
}
Run Code Online (Sandbox Code Playgroud)
这是我应该避免的吗?传递一个对象以便使用对象方法更好吗?布尔值finished现在是否计为全局,或者它是否同样安全?
这可能是一个初学者的问题,问题与理解为什么我们需要将服务注入组件有关.
1]当我们只能创建一个静态方法时,为什么我们需要将服务注入每个组件,它将返回相同的输出,我们真的不需要继续编写额外的代码来注入这些服务?
假设我有一个类似下面的身份验证服务,具有正常约定:
import { Injectable } from '@angular/core';
import { Http, Response, Headers } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/map';
import { GlobalConfig } from "../global-config";
// Models
import { UserModel } from "../models/user-model";
@Injectable()
export class AuthenticationService {
constructor(private http: Http) { }
authenticate(user: UserModel): Observable<UserModel> {
let userObject = this.http.post(GlobalConfig.getUrlFor('authentication'), user)
.map((response: Response) => {
let responseJSON = response.json();
let userObj = <UserModel>{
UserId: responseJSON.UserId,
FirstName: responseJSON.FirstName,
LastName: responseJSON.LastName,
FullName: responseJSON.FullName,
Email: responseJSON.Email, …Run Code Online (Sandbox Code Playgroud)