可能重複:
Finding the Variable Name passed to a Function in C#如何將變量名稱轉換爲c#.net中的字符串?
public new Dictionary<string, string> Attributes { get; set; }
public string StringAttributes = string.Empty;
public int? MaxLength { get; set; }
public int? Size { get; set; }
public int? Width { get; set; }
public int? Height { get; set; }
protected override void OnInit(EventArgs e) {
Attributes = new Dictionary<string, string>();
Attributes.Add("MaxLength", MaxLength.ToString());
Attributes.Add("Size", Size.ToString());
Attributes.Add("Width", Width.ToString());
Attributes.Add("Height", Height.ToString());
base.OnInit(e);
}
protected override void OnPreRender(EventArgs e) {
if (Attributes != null) {
StringBuilder attributes = new StringBuilder();
foreach (var item in Attributes) {
if (!string.IsNullOrWhiteSpace(item.Value)) {
attributes.Append(item.Key + "=\"" + item.Value + "\" ");
}
}
StringAttributes = attributes.ToString();
}
}
這裏的問題是,而是採用Attributes.Add("MaxLength", MaxLength.ToString());
重複其他性質相同的過程,可能我們不只是做一個函數,還能夠爲字典添加值,其中要添加的鍵是它們的變量名稱? 說,
public void addAttribute(object variable){
Attributes = new Dictionary<string, string>();
Attributes.Add(variable.Name, variable.Value);
}...
我想這也是可以做到與反思,讓所有的空的屬性,並通過然後將它們添加到每個字典循環......但只要有任何其他的方式,我們不會堅持反思。
但如果反射是唯一的選擇,那麼另一個問題現在是如何獲取類的空的屬性...
任何幫助將不勝感激。謝謝。
看一看:
在我的示例代碼中的反射,因爲它是我的通用檢查類的靜態構造函數中執行的每種類型的檢查執行一次, http://stackoverflow.com/questions/72121/finding-the-variable-name-passed-to-a-function-in-c – adrianbanks 2009-12-02 23:34:52
我不知道我們可以使用這個表達式... '公共字符串GetPropertyName(表達式>變量){ return(variable.Body as MemberExpression).Member.Name; }' –
Jronny
2009-12-03 03:43:05
是的,這個問題在這裏不止一次被問到。這裏是一個更多的鏈接:http://stackoverflow.com/questions/1669016/how-do-you-get-a-c-property-name-as-a-string-with-reflection – 2009-12-03 19:09:49