使用反射获取字典值

Tim*_*Tim 6 c# reflection dictionary

我试图访问存储在String,UnknownClass类型的字典中的对象.我有密钥,并且知道值是几个容器类之一.由于值传递给接受对象的方法,因此我不需要知道存储为值的类的类型.我还需要调用ContainsKey来确认密钥是否存在.

我尝试了以下方法但没有成功:

Dictionary<String, object> list = (Dictionary<String, object>)source.GetType().GetProperty(dictionaryName).GetValue(source, null);
nextSource = list[key];
Run Code Online (Sandbox Code Playgroud)

这给了我一个投射错误,并且:

nextSource = source.GetType().GetMethod("get_Item").Invoke(source, new object[] { key });
Run Code Online (Sandbox Code Playgroud)

这给了我一个空的引用异常.

这里有一些代码,虽然我不太确定它会有多大帮助.

private void SetValue(object source, String path, String value)
{
    if (path.Contains('.'))
    {
        //  If this is not the ending Property, continue recursing
        int index = path.IndexOf('.');
        String property = path.Substring(0, index);

        object nextSource;
        if(property.Contains("*"))
        {
            path = path.Substring(index + 1);
            index = path.IndexOf('.');
            String dictionaryName = path.Substring(0, index);

            Dictionary<String, object> list = (Dictionary<String, object>)source.GetType().GetProperty(dictionaryName).GetValue(source, null);
            nextSource = list[property.Substring(1)];
            //property = property.Substring(1);
            //nextSource = source.GetType().GetMethod("Item").Invoke(source, new[] { property });
        } ...
Run Code Online (Sandbox Code Playgroud)

正在访问的字典在PersonObject类中定义如下:

public class PersonObject
{
    public String Name { get; set; }
    public AddressObject Address { get; set; }
    public Dictionary<String, HobbyObject> Hobbies { get; set; }
Run Code Online (Sandbox Code Playgroud)

在此阶段,Path的值设置为"*Hiking.Hobbies.Hobby".基本上,路径字符串允许我导航到子类中的Property,我需要Dictionary来访问同一类列表的属性.

dtb*_*dtb 8

字典<TKEY的,TValue>中类实现非通用的IDictionary接口.因此,如果您有一个object包含对Dictionary<String, HobbyObject>实例的引用的tye变量,您可以按如下方式检索字典中的值:

object obj = new Dictionary<String, HobbyObject>
{
    { "Hobby", new HobbyObject() }
};

IDictionary dict = obj as IDictionary;
if (dict != null)
{
    object value = dict["Hobby"];
    // value is a HobbyObject
}
Run Code Online (Sandbox Code Playgroud)