CLI/C# 类中属性的特殊访问控制
我试图强制使用我的类的代码始终直接获取它的属性之一——永远不要保存它并单独使用它。例如,我希望以下内容无法编译。
int x = myObj->prop1;
int y = x + 1;
我想强迫他们获得这样的值:
int y = myObj->prop1 + 1;
我猜这是不可能的,但我想如果是的话,那么这里的人就会知道。
如果您想知道原因,这很复杂,但与强制代码以与该类的未来迭代向前兼容的方式使用我的类有关。
I'm trying to force the code that uses my class to always get one of it's properties directly -- never save it and use it separately. For example, I want the following to be uncompilable.
int x = myObj->prop1;
int y = x + 1;
I want to force them to get the value like this:
int y = myObj->prop1 + 1;
I'm guessing it's not possible, but I figure if it is then someone here will know.
If you want to know why, it's complicated but has to do with forcing the code to use my class in a way that is forward-compatible with a future iteration of the class.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以返回某种不可复制的代理,而不是存储变量的实例。但请考虑,对于值类型,返回的实例是您的属性支持字段的完全独立的副本,因此您的库的客户端不可能造成“任何伤害”...嗯,也许您应该在中解释您的意图更详细...
You could return some kind of non-copyable proxy instead of an instance of the stored variable. But please consider that for value types, the returned instance is a completely indepent copy of the backing field of your property so the client of your library has no possibility to do 'any harm'... Hm, maybe you should explain your intent in more detail...
我试图返回对对象的引用,但不允许用户存储该引用——“int”示例不太适合说明这一点(抱歉)。当您返回参考资料时,所有的赌注都会被取消,所以我想要做的事情具体是不可能的。
然而,我现在意识到,如果你想这样做,你需要你的财产不成为参考。只要您可以用非托管对象表示您的属性,这是可能的。
例如,我的“Foo”类有一个具有 X 和 Y 值的“Point”引用。
我可以向 Foo 添加一个属性,该属性返回带有 X 和 Y 值的结构,而不是对对象本身的引用。
然后外部对象可以看到 Point 对象的值,但不会干扰对象本身。
另一种方法是使“Point”成员/方法主要是内部的,因此当 Foo 将其作为属性返回时,外部程序集除了读取 XY 值之外实际上不能做太多事情。
感谢大家的关注!
I was trying to return a reference to an object but not allow the user to store the reference -- the "int" example was a bad one to illustrate this (sorry). When you return a reference, all bets are off, so what I was trying to do isn't possible specifically.
However, I realize now that if you want to do this, you need your property to NOT be a reference. As long as you can represent your property with an unmanaged object, this is possible.
For example, my "Foo" class has a "Point" reference that has X and Y values.
I can add a property to Foo that returns a struct with the X and Y values, not the reference to the object itself.
Then an external object can see the value of the Point object but not mess with the object itself.
Another way is to make the "Point" members/methods mostly internal so when Foo returns it as a property, an external assembly can't really do much but read the X Y values.
Thanks for the attention everyone!