[英]C# Accessing object properties indexer style
是否有任何工具,庫可以讓我訪問我的對象屬性索引器樣式?
public class User
{
public string Name {get;set;}
}
User user = new User();
user.Name = "John";
string name = user["Name"];
也許動態關鍵詞可以幫助我嗎?
您可以使用反射來獲取其名稱的屬性值
PropertyInfo info = user.GetType().GetProperty("Name");
string name = (string)info.GetValue(user, null);
如果你想使用索引,你可以試試這樣的東西
public object this[string key]
{
get
{
PropertyInfo info = this.GetType().GetProperty(key);
if(info == null)
return null
return info.GetValue(this, null);
}
set
{
PropertyInfo info = this.GetType().GetProperty(key);
if(info != null)
info.SetValue(this,value,null);
}
}
看看這個關於索引。 字典存儲所有值和鍵而不是使用屬性。 這樣,您可以在運行時添加新屬性而不會降低性能
public class User
{
Dictionary<string, string> Values = new Dictionary<string, string>();
public string this[string key]
{
get
{
return Values[key];
}
set
{
Values[key] = value;
}
}
}
您當然可以繼承DynamicObject並以此方式執行。
http://msdn.microsoft.com/en-us/library/system.dynamic.dynamicobject.trygetindex.aspx
使用其他人提到的簡單索引器方法會限制您只返回'object'(並且必須轉換)或者只在類中使用字符串類型。
編輯 :正如其他地方所提到的,即使使用動態,您仍然需要使用反射或某種形式的查找來檢索TryGetIndex函數內的值。
在類實現Indexer之前,您不能這樣做。
如果您只想基於字符串值訪問屬性,可以使用反射來執行類似的操作:
string name = typeof(User).GetProperty("Name").GetValue(user,null).ToString();
您可以使用反射和索引器自己構建它。
但是你需要什么樣的解決方案呢?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.