c# - 如何在运行时在 expando 上添加对象属性?

标签 c# model-view-controller expandoobject

我读了一些关于 expando 对象的文章 here但我想实现不同的目标。
我想在运行时添加具有动态属性的属性对象,为其赋值然后稍后检索:

    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)  

最佳答案

使用 conditionalWeakTable 和动态,您可以在几行中实现动态扩展属性:

using System.Dynamic;
using System.Runtime.CompilerServices;

namespace ExtensionProperties
{
    /// <summary>
    /// Dynamically associates properies to a random object instance
    /// </summary>
    /// <example>
    /// var jan = new Person("Jan");
    ///
    /// jan.Age = 24; // regular property of the person object;
    /// jan.DynamicProperties().NumberOfDrinkingBuddies = 27; // not originally scoped to the person object;
    ///
    /// if (jan.Age &lt; jan.DynamicProperties().NumberOfDrinkingBuddies = 27)
    /// Console.WriteLine("Jan drinks too much");
    /// </example>
    /// <remarks>
    /// If you get 'Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create' you should reference Microsoft.CSharp
    /// </remarks>
    public static class ObjectExtensions
    {
        ///<summary>Stores extended data for objects</summary>
        private static ConditionalWeakTable<object, object> extendedData = new ConditionalWeakTable<object, object>();

        /// <summary>
        /// Gets a dynamic collection of properties associated with an object instance,
        /// with a lifetime scoped to the lifetime of the object
        /// </summary>
        /// <param name="obj">The object the properties are associated with</param>
        /// <returns>A dynamic collection of properties associated with an object instance.</returns>
        public static dynamic DynamicProperties(this object obj) => extendedData.GetValue(obj, _ => new ExpandoObject());
    }
}

使用示例在xml注释中:

var jan = new Person("Jan");

jan.Age = 24; // regular property of the person object;
jan.DynamicProperties().NumberOfDrinkingBuddies = 27; // not originally scoped to the person object;

if (jan.Age && jan.DynamicProperties().NumberOfDrinkingBuddies == 27)
{
    Console.WriteLine("Jan drinks too much");
}

关于c# - 如何在运行时在 expando 上添加对象属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11256188/

相关文章:

c# - ZeroMQ/ØMQ/0MQ 如何入门?

c# - 使用 PagedList 对产品列表进行分页

c# - 在 Linq 中处理临时计算

java - 如何避免静态资源请求被路由到拦截器?

java - Spring 在服务器上运行良好,但在主应用程序上运行不佳

c# - c# 动态 ExpandoObjects 名称中的句点?

c# - MVC 在不注销的情况下授权属性工作

php - 创建 "Engine"以允许集成到主 Web 应用程序?

c# - 将嵌套属性动态添加到 ExpandoObject

c# - 为什么我不能在隐式转换时返回接口(interface),而 ExpandoObject 可以?