1

是否可以使用 C# 自动属性来创建对象的新实例?

在 C# 中,我喜欢如何做到这一点:

public string ShortProp {get; set;}

是否可以对像 List 这样首先需要实例化的对象执行此操作?

IE:

List<string> LongProp  = new List<string>(); 
public List<string> LongProp {  
    get {  
        return LongProp ;  
    }  
    set {  
         LongProp  = value;  
    }  
}
4

5 回答 5

8

您可以在构造函数上初始化支持字段:

public class MyClass {
    public List<object> ClinicalStartDates {get; set;}
    ...
    public MyClass() {
        ClinicalStartDates = new List<object>();
    }
}

但是...您确定要将此列表设为具有公共设置器的属性吗?我不知道您的代码,但也许您应该减少类的属性:

public class MyClass {
    public List<object> ClinicalStartDates {get; private set;}
    ...
    public MyClass() {
        ClinicalStartDates = new List<object>();
    }
}
于 2009-08-13T23:36:31.627 回答
1

您必须在构造函数中对其进行初始化:

class MyClass {

  public MyClass() {
    ShortProp = "Some string";
  }

  public String ShortProp { get; set; }

}
于 2009-08-13T23:35:04.533 回答
0

我从不想在类定义中声明一个变量。在构造函数中执行它。

所以按照这个逻辑,你可以在你的类的构造函数中初始化你的 ShortProp。

于 2009-08-13T23:35:21.863 回答
0

您可以做到这一点的唯一方法是在构造函数中。


public List<ClinicalStartDate> ClinicalStartDates { get; set; }

public ObjCtor()
{
   ClinicalStartDates = new List<ClinicalStartDate>;
}

不过,这可能不是你想听到的。

于 2009-08-13T23:35:23.237 回答
0

C# 3.5 不支持自动属性的自动初始化
所以是的,你应该使用构造函数
你的问题是重复

于 2009-08-13T23:45:33.290 回答