C#访问对象属性索引器样式

use*_*034 9 c#

是否有任何工具,库可以让我访问我的对象属性索引器样式?

public class User
{
    public string Name {get;set;}
}

User user = new User();
user.Name = "John";

string name = user["Name"];
Run Code Online (Sandbox Code Playgroud)

也许动态关键词可以帮助我吗?

Ste*_*cya 10

您可以使用反射来获取其名称的属性值

   PropertyInfo info = user.GetType().GetProperty("Name");
   string name = (string)info.GetValue(user, null);
Run Code Online (Sandbox Code Playgroud)

如果你想使用索引,你可以试试这样的东西

    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);
        }
    }
Run Code Online (Sandbox Code Playgroud)


Osk*_*lin 3

查看有关索引器的内容。字典存储所有值和键,而不是使用属性。这样您就可以在运行时添加新属性而不会损失性能

public class User
{
    Dictionary<string, string> Values = new Dictionary<string, string>();
    public string this[string key]
        {
            get
            {
                return Values[key];
            }
            set
            {
                Values[key] = value;
            }
        }
}
Run Code Online (Sandbox Code Playgroud)