将一个类设置为静态只是阻止人们尝试创建它的实例。如果你的类中只有静态成员,那么将类本身设置为静态是一个好习惯。
static class CollegeRegistration
{
//All static member variables
static int nCollegeId; //College Id will be same for all the students studying
static string sCollegeName; //Name will be same
static string sColegeAddress; //Address of the college will also same
//Member functions
public static int GetCollegeId()
{
nCollegeId = 100;
return (nCollegeID);
}
//similarly implementation of others also.
} //class end
public class student
{
int nRollNo;
string sName;
public GetRollNo()
{
nRollNo += 1;
return (nRollNo);
}
//similarly ....
public static void Main()
{
//Not required.
//CollegeRegistration objCollReg= new CollegeRegistration();
//<ClassName>.<MethodName>
int cid= CollegeRegistration.GetCollegeId();
string sname= CollegeRegistration.GetCollegeName();
} //Main end
}
静态类在某些情况下很有用,但滥用或过度使用它们可能存在潜在问题,就像大多数语言特性一样。
正如Dylan Smith已经提到的那样,使用静态类最明显的情况是当你有一个只包含静态方法的类时。允许开发人员实例化这样的类没有任何意义。
需要注意的是,过多的静态方法本身可能表明你的设计策略有缺陷。我发现当你创建一个静态函数时,询问自己这个问题很有帮助--它最适合作为a)实例方法还是b)接口扩展方法。这里的思想是对象行为通常与对象状态相关联,这意味着该行为应该属于对象。使用静态函数意味着该行为不应属于任何特定的对象。
在多态和接口驱动的设计中,过度使用静态函数会受到限制--它们不能在派生类中重写,也不能附加到接口上。通常最好通过接口的扩展方法将“辅助”函数绑定到接口上,从而使所有接口实例都可以访问共享的“辅助”功能。
在我的意见中,静态函数绝对有用的一个情况是在创建.Create()或.New()方法以实现对象创建逻辑时,例如当你想代理正在创建的对象时。
public class Foo
{
public static Foo New(string fooString)
{
ProxyGenerator generator = new ProxyGenerator();
return (Foo)generator.CreateClassProxy
(typeof(Foo), new object[] { fooString }, new Interceptor());
}
这可以与代理框架(如Castle Dynamic Proxy)一起使用,其中您想要拦截/注入对象的功能,基于其方法分配的某些属性。总体思路是需要一个特殊的构造函数,因为从技术上讲,您正在创建具有特殊添加功能的原始实例的副本。