我有这样的情况,我试图访问一个静态属性,该属性包含一个对象的单例,我希望仅通过知道其类型来检索该对象。我有一个实现,但它看起来很麻烦......
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 访问公共(public)静态属性?
谢谢
最佳答案
您可以通过调用 PropertyInfo.GetValue
稍微简化它相反:
SelectedValue = (IFace)SelectedType
.GetProperty("Instance", BindingFlags.Static | BindingFlags.Public)
.GetValue(null, null);
从 .NET 4.5 开始,您可以调用 GetValue(null)
作为已添加的重载,它没有索引器参数的参数(如果您明白我的意思)。
此时它与反射一样简单。正如 David Arno 在评论中所说,您很可能应该重新审视设计。
关于c# - 从 System.Type 获取静态属性的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19444838/