我在这里阅读了一些关于 expando 对象的文章,但我想实现不同的目标。
我想在运行时添加具有动态属性的属性对象,为其赋值,然后稍后检索:
private static readonly ConditionalWeakTable<object, ExpandoObject> props = new ConditionalWeakTable<object, ExpandoObject>();
public static void AddDataExtension(this object key, dynamic value)
{
props.Add(key, value);
}
public static dynamic GetDataExtension(this object key)
{
ExpandoObject ex = null;
return props.TryGetValue(key, out ex);
}
用法:
'Insert data at runtime'
instance.AddDataExtension("Hello", "hi");
'Get the data at runtime'
instance.GetDataExtension("Hello")
但我收到此错误:
The best overloaded method match for 'System.Runtime.CompilerServices.ConditionalWeakTable<object,System.Dynamic.ExpandoObject>.Add(object, System.Dynamic.ExpandoObject)' has some invalid arguments
我想我滥用了这个属性,这可能实现吗?如果是,如何?请帮忙。
编辑
这是完整的课程:
public static class instance
{
private static readonly ConditionalWeakTable<object, ExpandoObject> props = new ConditionalWeakTable<object, ExpandoObject>();
public static void AddDataExtension(this object key, dynamic value)
{
props.Add(key, value);
}
public static dynamic GetDataExtension(this object key)
{
ExpandoObject ex = null;
return props.TryGetValue(key, out ex);
}
}
我想要实现的是:
我将有随机变量,例如,“ photo_01, photo_12, photo_15, name_01, name_02, age_01, age_02
”
如果可能的话,我想以这种方式使用该方法:
id = <fetch from dbase>
instance.AddDataExtension("photo_" + id, byte[]);
然后检索值:
instance.GetDataExtension("photo_" + id)