简体   繁体   中英

Get the value of a static property from a System.Type

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM