日期:2014-05-18 浏览次数:21066 次
public class A
{
public static A _This = null;
public static A This
{
get
{
if (_This == null)
_This = new A();
return _This;
}
}
private static string _TestStr = "";
public string TestStr
{
get { return _TestStr; }
set { _TestStr = value; }
}
public void ConsoleStr()
{
Console.Write(TestStr);
}
}
class Program
{
static void Main(string[] args)
{
A.This.TestStr = "aaa";
A.This.ConsoleStr();
A a = new A();
a.ConsoleStr();
Console.ReadKey();
}
}
------解决方案--------------------
[Quote=引用:]
[code=C#][/code]这种 "在静态函数中实例化自己并给类属性赋值" 的优点在哪呢?
[/Quote]
类似于全局变量,这就好像一个全局对象,任何地方来访问都是唯一的对象,不会因为你的实例而改变内容,也可以根据自己的需要来扩展成局部的应用,