如何在C#中声明要使用的变量["name1"]

aka*_*ari 2 c#

我想在C#中声明一个这样的变量

public anyType variable;
Run Code Online (Sandbox Code Playgroud)

然后我可以像这样使用它

variable["name1"] = anyValue1;
variable["name2"] = anyValue2;
Run Code Online (Sandbox Code Playgroud)

我找不到任何解决方案来声明使用哪种类型的变量.
请帮我.

我感谢任何评论


附加信息:我有一节课:

public class Template
{
    public string Name {get; set; }
    public string Content {get; set;}
}
Run Code Online (Sandbox Code Playgroud)

我想像这样设置模板内容和模板名称的值

Template t = new Template();
t["Name"] = "template1";
t["Content"] = "templatecontent1";
Run Code Online (Sandbox Code Playgroud)

不:

Template t = new Template();
t.Name = "template1";
t.Content = "templatecontent1";
Run Code Online (Sandbox Code Playgroud)

我的意思是像一个表属性.这里我有表格模板,它有2列名称和内容.这样我就可以查询Template ["Name"]和Template ["Content"]
谢谢

Fly*_*179 7

你需要的类型是Dictionary<string, object>.您可以替换object任何类型的anyValue1anyValue2.

编辑:要允许索引器设置属性,你几乎肯定需要反思.在你的Template课上试试这个setter :

public string this[string field]
{
  get
  {
    PropertyInfo prop = GetType().GetProperty(field);
    return prop.GetValue(this, null);
  }
  set
  {
    PropertyInfo prop = GetType().GetProperty(field);
    prop.SetValue(this, value, null);
  }
}
Run Code Online (Sandbox Code Playgroud)

在上面的例子中没有错误处理,所以如果你尝试设置一个不存在的属性,或者不是一个字符串,或者没有一个getter/setter,它将会非常失败.您需要添加using System.Reflection到您的使用条款.


Mar*_*ers 5

您可以在索引器上看到本教程.

public Foo this[string index] 
{
    get { /* ... */ }
    set { /* ... */ }
}
Run Code Online (Sandbox Code Playgroud)