Access property by Index

2020-02-11 08:03发布

问题:

I need to access a property by an index or something similar. The reason why is explained in this already answered question. That answer uses Linq and I prefer something without that dependency. I have no control over the class.

public class myClass
{
    private string s = "some string";
    public string S
    {
        get { return s; }
    }
}

class Program
{
    static void Main(string[] args)
    {
        myClass c = new myClass();
        // I would like something similar
        // or same functionality
        string s = c["S"];
    }
}

回答1:

use (EDIT - as per comment):

string s = c.GetType().GetProperty ("S").GetGetMethod().Invoke (c, null).ToString();

It gives you the value of the (public) property named S of the the instance c regardless of the type of c and doesn't use LINQ at all although I must admit that I don't see why LINQ should be a problem...



回答2:

As you have no control over the class you can use extension method and reflection to get property value by name:

static class ObjectExtensions
{
    public static TResult Get<TResult>(this object @this, string propertyName)
    {
        return (TResult)@this.GetType().GetProperty(propertyName).GetValue(@this, null);
    }
}

Usage:

class A
{
    public string Z
    {
        get;
        set;
    }

    public int X
    {
        get;
        set;
    }
}

class Program
{
    static void Main(string[] args)
    {
        A obj = new A();
        obj.Z = "aaa";
        obj.X = 15;

        Console.WriteLine(obj.Get<string>("Z"));
        Console.WriteLine(obj.Get<int>("X"));
        Console.ReadLine();

    }
}


回答3:

You can achieve the same thing by using a default property on your class and a collection. Provided that you will always want strings, you could use the Dictionary class as your default property.

Then in the constructor you could intialize myDictionary["s"] = "some string";

You could then use the myClass as a collection, so myClass["s"] would return "some string".

Reflection is usually an indicator that you haven't created an API to do the job you need, if you have the code to modify then I recommend you use the default property.

See this MSDN article:



标签: c# reflection