更新泛型类的泛型属性?
我对 C# 泛型类
很陌生,所以我不知道我们是否可以动态更新泛型类的泛型属性?
假设我有一个类,
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}
如有任何帮助,我们将不胜感激!
I'm quite new at C# Generic Classes
so I don't know if we can update the generic property of a generic class dynamically?
Let say I have a class
A { long id; long count; }
Can we write an extension that update the given property by 1 so
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}
Any helps would be appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果我正确理解您的问题,您希望能够通过为
AddOne
方法提供 lambda 表达式来声明要更新的属性。在这种情况下,这是可能的——您可以编写一个扩展方法,该方法采用Expression
,从此表达式中检索属性访问表达式,并使用 Reflection 更新上的该属性一个对象。
以下是上述内容的一个非常粗略的原型:
If I understand your question correctly, you want to be able to declare which property to update by giving the
AddOne
method a lambda expression. In this case, it's possible -- you can write an extension method that takes anExpression<T>
, retrieves from this expression the property access expression, and uses Reflection to update that property on theA
object.The following is a very rough prototype of the above: