我正在尝试访问存储在String,UnknownClass类型的字典中的对象。我有密钥,并且知道值是几个容器类之一。由于值传递给接受对象的方法,因此我不需要知道存储为值的类的类型。我还需要调用ContainsKey来确认密钥是否存在。
我尝试了以下方法但没有成功:
Dictionary<String, object> list = (Dictionary<String, object>)source.GetType().GetProperty(dictionaryName).GetValue(source, null);
nextSource = list[key];
这给了我一个投射错误,并且:
nextSource = source.GetType().GetMethod("get_Item").Invoke(source, new object[] { key });
这给了我一个空的引用异常。
这里有一些代码,虽然我不太确定它会有多大帮助。
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 });
} ...
正在访问的字典在PersonObject类中定义如下:
public class PersonObject
{
public String Name { get; set; }
public AddressObject Address { get; set; }
public Dictionary<String, HobbyObject> Hobbies { get; set; }
在此阶段,Path的值设置为"*Hiking.Hobbies.Hobby"
。基本上,路径字符串允许我导航到子类中的Property,我需要Dictionary来访问同一类列表的属性。
答案 0 :(得分:7)
Dictionary<TKey, TValue> Class实现了非通用IDictionary Interface。因此,如果您有一个包含对object
实例的引用的tye Dictionary<String, HobbyObject>
变量,您可以按如下方式检索字典中的值:
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
}
答案 1 :(得分:3)
听起来你正试图这样做:
var source = new Dictionary<string, object>();
var key = "some key";
source.Add(key, "some value");
var property = source.GetType().GetProperty("Item");
var value = property.GetValue(source, new[] { key });
Console.WriteLine(value.ToString()); // some value
更新:问题是Dictionary<string, HobbyObject>
无法投放到Dictionary<string, object>
。我想你必须这样做:
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[0] = '*')
{
path = path.Substring(index + 1);
index = path.IndexOf('.');
String dictionaryName = path.Substring(0, index);
property = property.Substring(1);
Object list = source.GetType().GetProperty(dictionaryName)
.GetValue(source, null);
nextSource = list.GetType().GetProperty("Item")
.GetValue(list, new[] { property });
}