从字符串表示中访问对象属性

时间:2010-03-19 08:21:23

标签: c# reflection actionscript

在actionscript中,可以通过以下方式访问对象的属性:

object["propertyname"]

在没有使用反射的情况下,c#中是否可以这样?

2 个答案:

答案 0 :(得分:2)

不,你必须使用反射 如果最多可以创建一个辅助扩展方法,如下例所示:

using System;

static class Utils {
    public static T GetProperty<T>(this object obj, string name) {
        var property = obj.GetType().GetProperty(name);
        if (null == property || !property.CanRead) {
            throw new ArgumentException("Invalid property name");
        }
        return (T)property.GetGetMethod().Invoke(obj, new object[] { });
    }
}

class X {
    public string A { get; set; }
    public int B { get; set; }
}

class Program {
    static void Main(string[] args) {
        X x = new X() { A = "test", B = 3 };
        string a = x.GetProperty<string>("A");
        int b = x.GetProperty<int>("B");
    }
}

然而,这并不好 首先是因为您在运行时错误中转换了编译时错误 其次,在这种情况下,反射所带来的表现是不合理的。 我认为这里最好的建议是你不应该尝试使用C#编程,就像它是ActionScript一样。

答案 1 :(得分:0)

您可以在班级中定义索引器:

public class IndexerTest
{
    private Dicionary<string, string> keyValues = new ...

    public string this[string key]
    {
         get { return keyValues[key]; }
         set { keyValues[key] = value; }
    }
}

并像这样使用它:

string property = indexerTest["propertyName"];
相关问题