GetValue from list of GetProperties without an instantiated object using reflection

867 views Asked by At
public class SomeClass
{
    public IBy Some1{ get { return By.CssSelector("span[id$=spanEarth]"); } }

    public IBy Some2 { get { return By.CssSelector("span[id$=spanWorm]"); } }

    public IBy Some3 { get { return By.CssSelector("span[id$=spanJim]"); } }
}

is the class, and I am using reflection in this fashion:

var gridRow = Type.GetType(typeof(SomeOtherClassInSameNamespace).AssemblyQualifiedName.Replace("SomeOtherClassInSameNamespace", "SomeClass"), true, true);

var rowList = gridRow.GetProperties().Where(p => p.PropertyType.Name.Contains("IBy")).ToList();

int i = 0;
foreach (var property in rowList)
{
    string test = property.GetValue(gridRow, null).ToString();
}

Which gives a runtime error for an objectType exception. How do I get the values from the list of properties using Reflection?

1

There are 1 answers

0
Jon Skeet On BEST ANSWER

gridRow is a reference to a Type object. The first parameter of GetValue is meant to be the target object - so it's like you're trying to access the SomeClass properties on a Type object. That's clearly not going to work.

While there are hacky ways of evaluating an instance property without having a reference to an instance - so long as the property doesn't use this - they really are pretty nasty.

If a property doesn't need any state within an object, make it a static property instead. At that point you can use null as the target, and it'll be fine:

public class SomeClass
{
    public static IBy Some1 { get { return By.CssSelector("span[id$=spanEarth]"); } }

    public static IBy Some2 { get { return By.CssSelector("span[id$=spanWorm]"); } }

    public static IBy Some3 { get { return By.CssSelector("span[id$=spanJim]"); } }
}
...

var gridRow = Type.GetType(typeof(SomeOtherClassInSameNamespace)
                              .AssemblyQualifiedName
                              .Replace("SomeOtherClassInSameNamespace", "SomeClass"),
                           true, true);
var rowList = gridRow.GetProperties(BindingFlags.Public | BindingFlags.Static)
                     .Where(p => p.PropertyType.Name.Contains("IBy"));

int i = 0;
foreach (var property in rowList)
{
    string test = property.GetValue(null, null).ToString();
    ...
}