rji*_*ski 4 c# system.reflection system.type
我遇到的情况是,我试图访问一个静态属性,该属性包含一个对象的单例,我希望仅通过知道其类型来检索该对象。我有一个实现,但看起来很麻烦......
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();
}
}
Run Code Online (Sandbox Code Playgroud)
有没有其他方法可以做到以上几点?使用 System.Type 访问公共静态属性?
谢谢
您可以通过调用PropertyInfo.GetValue来稍微简化它:
SelectedValue = (IFace)SelectedType
.GetProperty("Instance", BindingFlags.Static | BindingFlags.Public)
.GetValue(null, null);
Run Code Online (Sandbox Code Playgroud)
从 .NET 4.5 开始,您可以调用,GetValue(null)因为添加了一个没有索引器参数参数的重载(如果您明白我的意思)。
在这一点上,它就像反射一样简单。正如 David Arno 在评论中所说,您很可能应该重新审视设计。