如何创建对值字段的引用
C# 中有没有办法创建一个字段,该字段是对另一个值类型字段的引用?
class myClass
{
bool b1;
public void method1(ref bool b)
{
b1 = b;
}
}
我希望 b1 引用 b 的值,就像 b 引用原始参数的值一样,这样对 b1 的更改就会影响原始参数。
编辑:
我想要实现的是一个自动更新字段的 myCheckBox 类。请参阅:如何更改值来自事件处理程序内的参数?
Is there a way in C# to create a field which is a reference to another field which is a value type?
class myClass
{
bool b1;
public void method1(ref bool b)
{
b1 = b;
}
}
I want b1 to reference the value of b, just as b references the value of the original argument, so that changes to b1 will affect the original argument.
EDIT:
What I’m trying to achieve is a myCheckBox class which automatically updates a field. See: How do I change a value argument from within an event handler?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
当然!看看埃里克对此问题的回答:
在 C# 中设置成员字段的引用
Sure! Take a look at Eric's answer to this question:
Setting a ref to a member field in C#
嗯...当然有一种非常扭曲的方式:)。
那就是利用反射!
你无法获取字段的地址,但我们可以使用反射。
我警告你,反射比直接访问字段慢。
事实上,访问其他类的私有字段是一种非常糟糕的做法!
然而,当您无法控制其他人编写的代码时,有时对于一些肮脏的黑客攻击很有用。
这是例子,但我一直说,这不是一个好的做法,这里只是出于好奇和教育目的!
访问字段的另一种方法是使用属性或使用修改属性的类。
Well... there is a very contort way :) of course.
That is, using reflection!
You cannot get the address of a field, but we can use reflection.
Reflection is slower than accessing directly a field, i warn you.
And really, accessing private fields of other classes is a really bad practice!
Is however useful sometime for some dirty hacks when you don't have control of code written by other people.
Here the example, but i keep saying, it is not a good practice, is here only for curiosity and for educational purposes!
Fine another way to access your field, using properties or using a class that modify your properties.
看起来使用委托/事件可以更好地解决问题。
不要尝试做不可能的事情(强制值类型表现为引用类型),而是使用事件并在该值发生更改时触发它。
从呼叫者那里订阅此活动,您就可以开始了。
Looks like something that is better solved using delegates/events.
Instead of trying to do the impossible (force value types to behave as reference types), use an event and fire it whenever this value is changed.
Subscribe to this event from the caller/s and you are good to go.
不知道您想要什么,可以为此使用委托,但它听起来确实像代码味道:
Not knowing what you would want this for you could use a delegate for this, it does sound like a code smell though: