Reputation: 15322
I'm trying to get the names of the people in the below class. I can get the list of PropertyInfo just fine, indicating that People has Bob and Sally, but I can't get references to Bob and Sally. How do I do that?
public static class People
{
public static Person Bob { get; }
public static Person Sally { get; }
}
PropertyInfo[] properties = typeof(People).GetProperties();
foreach (PropertyInfo info in properties)
{
if (info.PropertyType == typeof(Person))
{
// how do I get a reference to the person here?
Person c = info.GetValue(?????, ?????) as Person;
if (null != c)
{
Console.WriteLine(c.Name);
}
}
}
edit changed null == c to null != c to get console.writeline to execute
Upvotes: 2
Views: 150
Reputation: 1
Here's the approach that I use, which I've thrown into its own method. This will return an array of objects that are all the instances that are statically available from the type you pass in. It should not matter if the original type is static or not.
using System;
using System.Linq;
using System.Reflection;
public static object[] RetrieveInstancesOfPublicStaticPropertysOfTypeOnType(Type typeToUse) {
var instances = new List<object>();
var propsOfSameReturnTypeAs = from prop in typeToUse.GetProperties(BindingFlags.Public | BindingFlags.Static)
where prop.PropertyType == typeToUse
select prop;
foreach (PropertyInfo props in propsOfSameReturnTypeAs) {
object invokeResult = typeToUse.InvokeMember(
props.Name,
BindingFlags.GetProperty,
null,
typeToUse,
new object[] { }
);
if (invokeResult != null) {
instances.Add(invokeResult);
}
}
return instances.ToArray();
}
Upvotes: 0
Reputation: 1503489
Use:
Person c = (Person) info.GetValue(null, null);
if (c != null)
{
Console.WriteLine(c.Name);
}
The first null is for the target of the property - which is null because it's a static property. The second null is to say that there aren't any indexer arguments, because this is just a property, not an indexer. (They're the same kind of member to the CLR.)
I've changed the use of the result from an as
to a cast as you're expecting the result to be a Person
, given that you're already checked the property type.
I've then reversed the order of the operands for the comparison with null, as well as reversing the sense - you don't want to try to print out c.Name
if you know that c
is null! In C# the old C++ idiom of if (2 == x)
to avoid accidental assignment is almost always pointless, as an if
condition has to be a bool
expression anyway. In my experience most people find the code more readable with the variable first and the constant second.
Upvotes: 1