苯苯的博客

新随笔 联系 管理
  21 Posts :: 0 Stories :: 3 Comments :: 0 Trackbacks

2008年7月8日 #

A static method is simply one that is disassociated from any instance of its containing class. The more common alternative is an instance method, which is a method whose result is dependent on the state of a particular instance of the class it belongs to.

For example, both of these statements would return precisely the same string, but accomplish it through different types of methods:

// ToString() is an instance method of the DateTime class.
//  Its result depends on the value of each DateTime instance.
return DateTime.Now.ToString();
 
// String.Format is a static method of the String class.
//  Its result is not related to any instance of the String.
return String.Format("{0}", DateTime.Now);

The key difference to understand is that a static method can be called without setting up a proper instance of the class it belongs to.

In a sense, it is a stateless method.

posted @ 2008-07-08 04:20 one 阅读(15) | 评论 (0)编辑

The final advantage of using const over readonly is performance: Known
constant values can generate slightly more efficient code than the variable
accesses necessary for readonly values. However, any gains are slight and
should be weighed against the decreased flexibility.
Be sure to profile
performance differences before giving up the flexibility.


const must be used when the value must be available at compile times:
attribute parameters and enum definitions, and those rare times when
you mean to define a value that does not change from release to release.
For everything else, prefer the increased flexibility of readonly constants.

posted @ 2008-07-08 04:08 one 阅读(14) | 评论 (0)编辑