I have the situation that I am trying to access a static property that contains a singleton to an object that I wish to retrieve only by knowing its type. I have an implementation but it seems cumbersome...
public interface IFace
{
void Start()
}
public class Container
{
public IFace SelectedValue;
public Type SelectedType;
public void Start()
{
SelectedValue = (IFace)SelectedType.
GetProperty("Instance", BindingFlags.Static | BindingFlags.Public).
GetGetMethod().Invoke(null,null);
SelectedValue.Start();
}
}
Is there other way to do the above? Access a public static property using a System.Type ?
Thanks
You can simplify it slightly by calling PropertyInfo.GetValue
instead:
SelectedValue = (IFace)SelectedType
.GetProperty("Instance", BindingFlags.Static | BindingFlags.Public)
.GetValue(null, null);
As of .NET 4.5 you could call GetValue(null)
as an overload has been added which doesn't have the parameter for indexer parameters (if you see what I mean).
At this point it's about as simple as reflection gets. As David Arno says in comments, you should quite possibly revisit the design instead.
See more on this question at Stackoverflow