如何在类声明期间将成员添加到字典中

时间:2018-04-10 17:29:52

标签: c#

如何将其他成员(在课堂声明期间)添加到字典中?有没有解决方法? (这只是一个例子,它不起作用,但显示了我想要实现的目标。

public class X{

      private Dictionary<string, string() texts = new Dictionary<string, string(){}; 
      .....
      .....
      .....
      .....
      ..... //hundreds of lines here
      .....
      .....
      .....
      .....
      texts["xyz"] = "hello";     // <---  I want to add it here, not in top. but now it fires error, as this should have happened in method as I see

      // constructor
      public X(){

      }
}

P.S。我不需要单行宣言,比如... = new Dictionary<string, string(){ {"xyz", "hello"} };

2 个答案:

答案 0 :(得分:1)

你不能在c#中这样做,你应该在构造函数

中完成
public X()
{
    texts["xyz"] = "hello"; 
}

答案 1 :(得分:-1)

据我所知,您需要使用C#语言的动态功能。你的问题不明确。无论如何,你可以这样做:

dynamic x = new ExpandoObject();

x.texts = new string[] { "zero", "one" };
x.//hundreds of lines here
x.texts[1] = "sdfgsdfg";
x.someMoreTexts = new string[] { "0", "1" };