简体   繁体   English

c#静态类属性

[英]c# Static Class Property

An example has been shown to me today, and just wanted to check if both of the following will in fact have the same effect, and it not, what the difference is between them. 我今天已经向我展示了一个例子,并且只想检查以下两者是否实际上具有相同的效果,而不是,它们之间的区别是什么。

Is this: 这是:

private static Service1Client _myFoo;

static ServiceLayer()
{
    MyFoo = new Service1Client();
}

public static Service1Client MyFoo
{
    get { return _myFoo; }
    set { _myFoo = value; }
}

Just a long winded way of doing this: 这是一个冗长的方式:

public static Service1Client _myFoo
{
    get { return _myFoo; }
    set { _myFoo = value; }
}

static ServiceLayer()
{
    _myFoo = new Service1Client();
}

If this isn't the case, what is the difference between them? 如果不是这样,那么它们之间有什么区别?

Thanks. 谢谢。

You need the backing field because: 您需要支持字段,因为:

public static Service1Client _myFoo
{
    get { return _myFoo; }
}

....like you have in your example will loop forever. ....就像你在你的例子中将永远循环。

However, C# does provide automatic properties. 但是,C#确实提供了自动属性。 You could accomplish the same thing with this simple code: 你可以用这个简单的代码完成同样的事情:

public static Service1Client MyFoo { get; set; }

static ServiceLayer()
{
    MyFoo = new Service1Client();
}

Almost, but no. 几乎,但没有。 In your public property, you can't return the object you're getting and setting. 在您的公共财产中,您无法返回您正在获取和设置的对象。 You need a backing field. 你需要一个支持领域。

private static Service1Client _myFoo
public static Service1Client MyFoo
{
     get { return _myFoo; }
     set { _myFoo = value; }
}

In this case since you're only doing a basic get and set, you can use an auto property. 在这种情况下,由于您只进行基本的get和set,因此可以使用auto属性。 This is equivalent to the code above. 这相当于上面的代码。

public static Service1Client MyFoo { get; set; }

Given this code: 鉴于此代码:

public static Service1Client _myFoo
{
    get { return _myFoo; }
    set { _myFoo = value; }
}

You will get a StackOverflowExcpetion any time you use the getter or the setter because the setter calls itself, which will call itself, etc (until you run out of stack space). StackOverflowExcpetion使用getter或setter时都会得到一个StackOverflowExcpetion ,因为setter会调用自身,它会调用自身等等(直到你的堆栈空间用完为止)。

One way of successfully shortening the first example would be: 成功缩短第一个例子的一种方法是:

public static Service1Client MyFoo {get;set;}

static ServiceLayer()
{
    MyFoo = new Service1Client();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM