简体   繁体   English

c#通过设置成员值实例化一个类

[英]c# Instantiate a class by setting a member value

Currently when setting a member variable of on object I check if the object is instantiated. 当前,当设置on对象的成员变量时,我检查对象是否被实例化。 Is this really necessary, or is the object instantiated by just setting one member variable? 这真的必要吗,还是仅通过设置一个成员变量来实例化对象?

Person _Person;      

public int Age
{
  get
  {
    return _Person.Age;
  }
  set
  {
    if (_Person != null)
      _Person.Age = value;
    else
      _Person = new _Person(value);
  }
}

Is that the same as below? 与下面相同吗?

Person _Person;      

public int Age
{
  get
  {
    return _Person.Age;
  }
  set
  {
    _Person.Age = value;
  }
}

No, you must instantiate to allocate the memory in the variable. 不,您必须实例化以在变量中分配内存。 With out instantiating the variable will be always equal to null 在没有实例化的情况下,变量将始终等于null

When an instance constructor has no constructor initializer, or it has a constructor initializer of the form base(...), that constructor implicitly performs the initializations specified by the variable-initializers of the instance fields declared in its class. 当实例构造函数没有构造函数初始值设定项,或者它具有base(...)形式的构造函数初始值设定项时,该构造函数将隐式执行由在其类中声明的实例字段的变量初始值设定项指定的初始化。 This corresponds to a sequence of assignments that are executed immediately upon entry to the constructor and before the implicit invocation of the direct base class constructor. 这对应于分配的序列,这些分配的序列在进入构造函数后立即执行,并且在隐式调用直接基类构造函数之前执行。

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

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