c# - 更新泛型类的泛型属性?

标签 c# dynamic propertychanged generics

我对 C# Generic Classes 很陌生,所以我不知道我们是否可以动态更新泛型类的泛型属性?

假设我有一个类

A { long id; long count; }

我们可以编写一个扩展,将给定属性更新 1 吗

A.AddOne(a => a.id); will change A {id=1, count=1} to A {id=2, count=1}

and

A.AddOne(a => a.count); will change A {id=1, count=1} to A {id=1, count=2}

如有任何帮助,我们将不胜感激!

最佳答案

如果我正确理解您的问题,您希望能够通过提供 AddOne 来声明要更新的属性方法 lambda 表达式。在这种情况下,有可能——您可以编写一个采用 Expression<T> 的扩展方法。 ,从此表达式中检索属性访问表达式,并使用反射更新 A 上的该属性对象。

以下是上述内容的一个非常粗略的原型(prototype):

public static void AddOne<S,T>(this S x, Expression<Func<S,T>> expr)
{
    if (expr.Body.NodeType != ExpressionType.MemberAccess)
        throw new InvalidOperationException();

    MemberExpression memberExpr = expr.Body as MemberExpression;
    switch (memberExpr.Member.MemberType)
    {
        case MemberTypes.Field:
            {
                FieldInfo field = memberExpr.Member as FieldInfo;
                ulong value = Convert.ToUInt64(field.GetValue(x));
                ++value;
                field.SetValue(x, Convert.ChangeType(value, field.FieldType));
                break;
            }
        case MemberTypes.Property:
            {
                PropertyInfo prop = memberExpr.Member as PropertyInfo;
                ulong value = Convert.ToUInt64(prop.GetValue(x, null));
                ++value;
                prop.SetValue(x, Convert.ChangeType(value, prop.PropertyType), null);
                break;
            }
        default:
            throw new InvalidOperationException();
    }
}

关于c# - 更新泛型类的泛型属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4807042/

相关文章:

C# foreach 派生类的行为?

javascript - JS : Get the . 所选数据列表选项的 html()

javascript - Skycons/Dark Sky Forecast API,显示动态创建的 DIV 的动画图标

WPF 过多的 PropertyChanged 事件

c# - 使模拟在更改时触发 PropertyChanged

c# - 为什么我使用 UpdateSourceTrigger=PropertyChanged ,TwoWay 还不够?

c# - 自动调用基方法

c# - 我想创建一个具有任意索引的 IEnumerable 继承稀疏数组

dynamic - SSRS动态边框

c# - Socket.SendAsync 需要几秒钟才能完成