繁体   English   中英

反射GetValue对于Uri类失败

[英]Reflection GetValue fails for Uri class

我想访问Uri类的m_Info字段以更改其中的某些字段。 但是uriInfo.GetValue(uri)返回null。

        var uri = new Uri("https://stackoverflow.com/questions/12993962/set-value-of-private-field");
        var uriInfo = typeof(Uri).GetField("m_Info", BindingFlags.NonPublic | BindingFlags.Instance);
        var infoField = uriInfo.GetValue(uri);

该代码对于与Uri具有相同结构的测试类正常工作,但对于System.Uri类却失败。 有任何想法吗?

很简单:在该代码路径中未分配 m_Info 在第一次需要时延迟分配它。 在本地,这有效:

object infoField = uriInfo.GetValue(uri); // null
var port = uri.Port; // forces it to initialize
infoField = uriInfo.GetValue(uri); // not null

但是请注意,这种方法本身并未完全包含在内。 在反射器中寻找.Port ,这仅适用于“简单语法”(无论什么意思):

if (this.m_Syntax.IsSimple)
{
    this.EnsureUriInfo();
}
else
{
    this.EnsureHostString(false);
}
if (this.InFact(Flags.HostNotParsed | Flags.NotDefaultPort))
{
    return this.m_Info.Offset.PortValue;
}
return this.m_Syntax.DefaultPort;

重点是:保证m_Info具有值是不平凡的。 您可能想尝试首先通过反射调用EnsureInfoInfo()方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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