C# Accessing object properties indexer style
Is there any tool,library that would allow me to access my objects properties indexer style ?
public class User
{
开发者_运维百科 public string Name {get;set;}
}
User user = new User();
user.Name = "John";
string name = user["Name"];
Maybe the dynamic key word could help me here ?
You can use reflection to get property value by its name
PropertyInfo info = user.GetType().GetProperty("Name");
string name = (string)info.GetValue(user, null);
And if you want to use index for this you can try something like that
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);
}
}
Check out this about indexers. The dictionary stores all the values and keys instead of using properties. This way you can add new properties at runtime without losing performance
public class User
{
Dictionary<string, string> Values = new Dictionary<string, string>();
public string this[string key]
{
get
{
return Values[key];
}
set
{
Values[key] = value;
}
}
}
You could certainly inherit DynamicObject and do it that way.
http://msdn.microsoft.com/en-us/library/system.dynamic.dynamicobject.trygetindex.aspx
Using the simple indexer method mentioned here by others would limit you to either returning only 'object' (and having to cast) or having only string types in your class.
Edit: As mentioned elsewhere, even with dynamic, you still need to use either reflection or some form of lookup to retrieve the value inside the TryGetIndex function.
You cannot do this until the class implements a Indexer.
If you just want to access a property based on a string value you could use reflection to do something similar:
string name = typeof(User).GetProperty("Name").GetValue(user,null).ToString();
You could build it yourself with reflection and indexer.
But for what do you need such a solution?
精彩评论