简体   繁体   English

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

[英]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. 您当然可以继承DynamicObject并以此方式执行。

http://msdn.microsoft.com/en-us/library/system.dynamic.dynamicobject.trygetindex.aspx 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. 使用其他人提到的简单索引器方法会限制您只返回'object'(并且必须转换)或者只在类中使用字符串类型。

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. 编辑 :正如其他地方所提到的,即使使用动态,您仍然需要使用反射或某种形式的查找来检索TryGetIndex函数内的值。

在类实现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? 但是你需要什么样的解决方案呢?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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