我们可以从构造函数访问属性

时间:2011-07-29 22:35:59

标签: c#

我正在研究一个CSharp代码,在构造函数中我需要访问该类的属性。从逻辑上讲,它对我来说很麻烦,因为我将访问尚未构建的对象的属性。

它是一个使用c#4.0版的旧代码,我有点重构它,这就是为什么不能从头开始重新设计所有东西。

由于

class employee
{
  employee()
  {
    int square = count * count;
  }
  private int count {get;set;}
} 

4 个答案:

答案 0 :(得分:3)

除此之外,count始终为0,这没有任何问题。

.Net中除了没有在构造函数中设置其所有状态的对象外,几乎没有“部分构造”对象。

答案 1 :(得分:1)

如果你正在构造类,并且之前在构造函数中没有设置任何属性,并且没有属性是静态的并且在其他地方设置,则值将是默认值或null,因此没有必要得到它们包含的内容。否则,构造函数是将属性设置为某些内容的理想位置。

答案 2 :(得分:0)

在构造时你可以设置一个属性,但除非它有一个静态成员支持获取或是一个值类型,否则在你设置之前你将得到一个空值。

public class WhatClass
{
    public WhatClass()
    {
        int theCount = Count; // This will set theCount to 0 because int is a value type
        AProperty = new SomeOtherClass; // This is fine because the setter is totally usable
        SomeOtherClass thisProperty = AProperty; // This is completely acceptable because you just gave AProperty a value;
        thisProperty = AnotherProperty; // Sets thisProperty to null because you didn't first set the "AnotherProperty" to have a value
    }

    public int Count { get; set; }
    public SomeOtherClass AProperty { get; set; }
    public SomeOtherClass AnotherProperty { get; set; }
}

答案 3 :(得分:0)

是的,C#允许这样做,但有时更好的私有字段由公共属性包装,而类方法只能用字段。在你的情况下,我建议删除私有属性,而使用类字段变量。如果您的类的消费者可能想要访问属性 - 使用私有的setter公开它,那么这种autmatic属性是由属性包装的privatr字段的另一种选择。

相关问题