我对 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/