初始化私有成员C# [英] Initializing private members c#

查看:218
本文介绍了初始化私有成员C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有需要的对象被创建时要进行初始化的两个专用列表。第二列表是依赖于第一个。我能做到这一点是这样的:

 公共类MyClass的
  {
      私人列表< T> myList上=新的名单,其中,T>();
      私人ReadOnlyCollection还< T> myReadOnlyList = myList.AsReadOnly;

      ...
  }
 

第二个列表是只读围绕第一个包装。

我能想到的是C#将这个顺序在每次运行时执行这两条线?

或者我应该把这个初始化的构造?

编辑:
对不起,愚蠢的问题。我试了一下,编译器说:

 错误1字段初始不能引用
             非静态字段,方法或属性...
 

解决方案

没有。如果你想基于类内的一个独立的变量初始化变量,你需要为此在构造函数中:

 公共类MyClass的
{
    私人列表< T> myList上=新的名单,其中,T>();
    私人ReadOnlyCollection还< T> myReadOnlyList;
    公共MyClass的()
    {
        myReadOnlyList = myList.AsReadOnly;
    }

}
 

内联intializers总是在静态情况下,这意味着你有你的类中没有访问成员变量运行。内部构造的,但是,你可以做到这一点。你的构造,这就是为什么我可以离开该列表初始化到位前,将发生的内联初始化。

I have two private lists that need to be initialized when object is created. Second list is dependent on first one. Can I do it like this:

  public class MyClass
  {
      private List<T> myList = new List<T>();
      private ReadOnlyCollection<T> myReadOnlyList = myList.AsReadOnly;

      ...
  }

Second list is read only wrapper around first one.

Can I expect that c# will execute this two lines in this order each time it is run?

Or should I put this initializations in constructor?

Edit:
Sorry for stupid question. I tried it and compiler says:

Error   1   A field initializer cannot reference the 
             non-static field, method, or property...

解决方案

No. If you want to initialize a variable based on a separate variable within the class, you need to do this in the constructor:

public class MyClass 
{ 
    private List<T> myList = new List<T>(); 
    private ReadOnlyCollection<T> myReadOnlyList;
    public MyClass()
    {
        myReadOnlyList = myList.AsReadOnly; 
    }

} 

Inlined intializers are always run in a static context, which means you have no access to member variables within your class. Inside of a constructor, however, you can do this. The inlined initializers will occur before your constructor, which is why I could leave the list initialization in place.

这篇关于初始化私有成员C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆