4

我有一种情况,我试图访问一个静态属性,该属性包含一个对象的单例,我希望只通过知道它的类型来检索它。我有一个实现,但它似乎很麻烦......

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();
    }
}

有没有其他方法可以做到以上?使用 System.Type 访问公共静态属性?

谢谢

4

1 回答 1

5

您可以通过调用PropertyInfo.GetValue来稍微简化它:

SelectedValue = (IFace)SelectedType
   .GetProperty("Instance", BindingFlags.Static | BindingFlags.Public)
   .GetValue(null, null);

从 .NET 4.5 开始,您可以调用GetValue(null)一个重载,它没有索引器参数的参数(如果您明白我的意思)。

在这一点上,它就像反射一样简单。正如 David Arno 在评论中所说,您很可能应该重新审视设计。

于 2013-10-18T08:30:47.780 回答