C# 复杂反射场景
我需要一些帮助,试图找到一种使用反射设置这行代码的方法:C# 复杂反射场景,c#,.net,reflection,field,C#,.net,Reflection,Field,我需要一些帮助,试图找到一种使用反射设置这行代码的方法: this.extensionCache.properties[attribute] = new ExtensionCacheValue((object[]) value); this.extensionCache是im继承自的基类中的内部私有字段 我可以使用以下代码访问extensionCache字段: FieldInfo field = typeof(Principal).GetFi
this.extensionCache.properties[attribute]
= new ExtensionCacheValue((object[]) value);
this.extensionCache是im继承自的基类中的内部私有字段
我可以使用以下代码访问extensionCache字段:
FieldInfo field = typeof(Principal).GetField("extensionCache",BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
但我不知道如何使用索引调用properties方法,然后将其设置为我无法查看的类的实例
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;
}
}
}
如果有背景帮助,我会尝试扩展System.DirectoryServices.AccountManagement.Principal,这是所有这些方法的所在
请参阅方法:ExtensionSet
谢谢你的帮助。首先;这种级别的反射通常是一种代码气味;保重 一步一个脚印;首先,我们需要获取
扩展缓存
:
FieldInfo field = typeof(Principal).GetField("extensionCache",
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
object extCache = field.GetValue(obj);
然后我们需要属性
:
field = extCache.GetType().GetField("properties",
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
IDictionary dict = (IDictionary) field.GetValue(extCache);
现在,您可以使用dict
上的索引器,使用新值:
dict[attribute] = ...
下一个问题是如何创建ExtensionCacheValue
;我假设您没有访问此类型(作为内部)的权限
有什么帮助吗
dict[attribute] = ...
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;