【问题标题】:Complex Reflection Scenario复杂反射场景
【发布时间】:2009-06-28 18:06:57
【问题描述】:

我需要一些帮助来尝试使用反射来设置这行代码:

this.extensionCache.properties[attribute]
                          = new ExtensionCacheValue((object[]) value);

this.extensionCache 是继承自基类的内部私有字段。

我可以使用以下代码访问 extensionCache 字段:

FieldInfo field = typeof(Principal).GetField("extensionCache",BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);

但我不知道如何使用索引调用属性方法,然后将其设置为我无法查看的类的实例。

extensionCache 属于以下类型:

internal class ExtensionCache
{
    private Dictionary<string, ExtensionCacheValue> cache
                   = new Dictionary<string, ExtensionCacheValue>();

    internal ExtensionCache()
    {
    }

    internal bool TryGetValue(string attr, out ExtensionCacheValue o)
    {
        return this.cache.TryGetValue(attr, out o);
    }

    // Properties
    internal Dictionary<string, ExtensionCacheValue> properties
    {
        get
        {
            return this.cache;
        }
    }
}

这是值类

internal ExtensionCacheValue(object[] value)
{
    this.value = value;
    this.filterOnly = false;
}

如果某些背景有助于我尝试扩展 System.DirectoryServices.AccountManagement.Principal 这是所有这些方法所在的地方。

参见方法:ExtensionSet

感谢您的帮助。

【问题讨论】:

    标签: c# .net reflection field


    【解决方案1】:

    首先;对此级别的反映通常是代码异味;保重……

    一步一个脚印;首先,我们需要得到ExtensionCache

    FieldInfo field = typeof(Principal).GetField("extensionCache",
        BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
    object extCache = field.GetValue(obj);
    

    那么我们需要properties:

    field = extCache.GetType().GetField("properties",
        BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
    IDictionary dict = (IDictionary) field.GetValue(extCache);
    

    您现在可以在dict 上使用索引器,并使用新值:

    dict[attribute] = ...
    

    接下来的问题是如何创建ExtensionCacheValue;我假设您无权访问此类型(作为内部)...

    Type type = extCache.GetType().Assembly.GetType(
          "Some.Namespace.ExtensionCacheValue");
    object[] args = {value}; // needed to double-wrap the array
    object newVal = Activator.CreateInstance(type, args);
    ...
    dict[attribute] = newVal;
    

    有什么帮助吗?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-27
      • 1970-01-01
      • 1970-01-01
      • 2021-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多