我遇到这种情况,我试图访问一个静态属性,该属性包含一个单例到我希望仅通过知道其类型来检索的对象。我有一个实现,但它似乎很麻烦......
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?
访问公共静态属性由于
答案 0 :(得分:4)
您可以通过调用PropertyInfo.GetValue
来轻微简化:
SelectedValue = (IFace)SelectedType
.GetProperty("Instance", BindingFlags.Static | BindingFlags.Public)
.GetValue(null, null);
从.NET 4.5开始,您可以调用GetValue(null)
,因为已经添加了一个没有索引器参数参数的重载(如果您看到我的意思)。
此时它就像反射一样简单。正如David Arno在评论中所说的那样,你很可能会重新考虑设计。