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

C# 如何在类声明期间将成员添加到字典中,c#,C#,如何将其他成员(在类声明期间)添加到字典中?有什么解决办法吗?(这只是一个例子,它不起作用,但显示了我想要实现的目标 public class X{ private Dictionary<string, string() texts = new Dictionary<string, string(){}; ..... ..... ..... ..... ..... //hundreds of lines he

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

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(){

      }
}
公共类X{

私人词典据我所知,你需要使用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" };
在c#中不能这样做,应该在构造函数中这样做

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

你得到的错误是什么?你尝试了什么?如果是数组或字典,这是非常不同的。你有哪一个?我们需要一个正确的-现在似乎你试图在任何方法之外设置数组元素不能在声明中完成,为类创建构造函数你在问如何初始化:
private string[]text=new[]{“hello”,“world”};
您可以在构造函数中动态设置值,也可以首先声明静态数组。我知道这在方法中是可能的,但我想说的是,我希望在出现
private int…..
声明的地方执行,而不是在方法或构造函数中。