在扩展方法保持状态 [英] Preserving state in an extension method

查看:167
本文介绍了在扩展方法保持状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C#团队以前考虑增加扩展属性,事件等为C#。

The C# team has previously considered adding extension properties, events, etc. to C#.

每埃里克利珀:

http://blogs.msdn.com/b/ericlippert/archive/2009/10/05/why-no-extension- properties.aspx

有关这些特性然而是有益的,他们将必须能够存储一些新样的状态与对象。好像要做到这一点是使用字典和对象与任何附加的状态是每个实例关联的唯一方式。

For these features to be useful however, they would have to be able to store some new kind of state with an object. It seems like the only way to do this would be to use a dictionary and associate each instance of an object with whatever the additional state is.

如果它是通过创建我自己的字典(也许是获取/设置扩展方法)来复制此功能手动这将是有益的。然而,为了一个特定的实例相关联的对象与一些国家则需要实际的参考的散列对象的的。在另一种语言,你可以这样做通过散列它的存储位置,但是在不能保证保持不变,并使用不安全的代码来完成这一功能的C#很不理想呢。

It would be useful if it were possible to copy this functionality "manually" by creating my own dictionary (and perhaps get/set extension methods). However, in order to associate a particular instance of an object with some state you would need to hash the actual reference to the object. In another language you might do this by hashing its memory location, however in C# that is not guaranteed to stay constant, and using unsafe code to accomplish this feature is far from ideal anyway.

有谁知道是否有可能获得一些哈希的对象引用不为对象的内部状态的改变而改变?有显然是一些内部机制来跟踪不论其存储位置的单个对象,但我不知道这是暴露在用户代码

Does anyone know if it's possible to get some hashable reference to an object that does not change as the object's internal state changes? There obviously is some internal mechanism to keep track of individual objects regardless of their memory location, but I'm not sure if that is exposed to user code.

请注意:只需散列对象本身不会在所有的工作,因为GetHashCode()方法依赖于对象的内部状态不在的哪个对象的是

Note: Simply hashing the object itself will not work at all, because GetHashCode() depends on an object's internal state not on which object it is.

谢谢任何见解。

推荐答案

您正在寻找的的 ConditionalWeakTable类

这篇关于在扩展方法保持状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆