简体   繁体   中英

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.

在类实现Indexer之前,您不能这样做。

如果您只想基于字符串值访问属性,可以使用反射来执行类似的操作:

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM