C# 什么';类的功能本身有一个静态成员吗?
例如:C# 什么';类的功能本身有一个静态成员吗?,c#,c++,static-members,C#,C++,Static Members,例如: class E { public static E e; //... }; 它的功能是什么?在什么情况下我们应该使用它?谢谢。static变量不能包含对实例中声明的任何其他内容的引用,而是静态变量/方法属于该类型而不是某个类型的实例 考虑这一点: public class TestClass { private static string _testStaticString; private string _testInstanceString;
class E
{
public static E e;
//...
};
它的功能是什么?在什么情况下我们应该使用它?谢谢。static变量不能包含对实例中声明的任何其他内容的引用,而是静态变量/方法属于该类型而不是某个类型的实例 考虑这一点:
public class TestClass
{
private static string _testStaticString;
private string _testInstanceString;
public void TestClass()
{
_testStaticString = "Test"; //Works just fine
_testInstanceString = "Test";
TestStatic();
}
private static void TestStatic()
{
_testInstanceString = "This will not work"; //Will not work because the method is static and belonging to the type it cannot reference a string belonging to an instance.
_testStaticString = "This will work"; //Will work because both the method and the string are static and belong to the type.
}
}
许多用法如此之多,足以填满书本。正如有人提到的,Singleton模式利用了它。其中一个用法是实现Singleton(当您需要一个只有一个实例的类,并且需要提供对该实例的全局访问点时):
它可能是任何东西。请提供单体或可能是某种原型对象。由于它在最后有半冒号,所以我认为它是C++问题。C++和C的答案可能不同。你在找哪一个?C#中单身人士的终极链接:
public class Singleton
{
private static Singleton instance;
private Singleton() {}
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}