[英]How to declare variable to use like that variable[“name1”] in C#
我想在C#中聲明一個這樣的變量
public anyType variable;
然后我可以像這樣使用它
variable["name1"] = anyValue1;
variable["name2"] = anyValue2;
我找不到任何解決方案來聲明使用哪種類型的變量。
請幫我。
我感謝任何評論
附加信息:我有一節課:
public class Template
{
public string Name {get; set; }
public string Content {get; set;}
}
我想像這樣設置模板內容和模板名稱的值
Template t = new Template();
t["Name"] = "template1";
t["Content"] = "templatecontent1";
不:
Template t = new Template();
t.Name = "template1";
t.Content = "templatecontent1";
我的意思是像一個表屬性。 這里我有表格模板,它有2列名稱和內容。 這樣我就可以查詢Template [“Name”]和Template [“Content”]
謝謝
你需要的類型是Dictionary<string, object>
。 您可以將object
替換為anyValue1
和anyValue2
的類型。
編輯:要允許索引器設置屬性,你幾乎肯定需要反思。 在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);
}
}
在上面的例子中沒有錯誤處理,所以如果你嘗試設置一個不存在的屬性,或者不是一個字符串,或者沒有一個getter / setter,它將會非常失敗。 您需要using System.Reflection
添加到您的uses子句。
您可以在索引器上看到本教程。
public Foo this[string index]
{
get { /* ... */ }
set { /* ... */ }
}
我認為你正在尋找索引器: link1 , link2 , link3
public class MyType
{
public string this[int index]
{
get
{
//getter implementation
}
set
{
//setter implementation
}
}
}
public class Usage
{
public MyType usageType = new MyType();
public Usage()
{
usageType[0] = "xx";
}
}
如果需要,可以隨時定義泛型類型: http : //msdn.microsoft.com/en-us/library/6x16t2tx.aspx ,使用字符串索引: http : //www.java2s.com/Code/CSharp/Language-基礎/ IndexingwithanStringIndex.htm
使用反射技術,但要認真謹慎。
public class Template
{
public string Name { get; set; }
public string Content { get; set; }
public string this[string name]
{
get
{
return typeof(Template).GetProperty(name).GetValue(this, null).ToString();
}
set
{
typeof(Template).GetProperty(name).SetValue(this, value, null);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.