如何在 C# 中存储对整数的引用? [英] How to store a reference to an integer in C#?
问题描述
可能的重复:
我如何通过引用"分配;到 c# 中的类字段?
大家好 - 请告诉我如何进行这项工作?基本上,我需要一个整数引用类型(int* 可以在 C++ 中工作)
Hello everyone - tell me how to make this work? Basically, I need an integer reference type (int* would work in C++)
class Bar
{
private ref int m_ref; // This doesn't exist
public A(ref int val)
{
m_ref = val;
}
public void AddOne()
{
m_ref++;
}
}
class Program
{
static void main()
{
int foo = 7;
Bar b = new Bar(ref foo);
b.AddOne();
Console.WriteLine(foo); // This should print '8'
}
}
我必须使用拳击吗?
也许我应该更具体.我正在编写一个 BitAccessor 类,它只允许访问单个位.这是我想要的用法:
Perhaps I should have been more specific. I'm writing a BitAccessor class, that simply allows access to individual bits. Here's my desired usage:
class MyGlorifiedInt
{
private int m_val;
...
public BitAccessor Bits {
return new BitAccessor(m_val);
}
}
用法:
MyGlorifiedInt val = new MyGlorifiedInt(7);
val.Bits[0] = false; // Bits gets a new BitAccessor
Console.WriteLine(val); // outputs 6
为了让 BitAccessor 能够修改 m_val,它需要对它的引用.但我想在很多地方使用这个 BitAccessor,只需要引用所需的整数.
For BitAccessor to be able to modify m_val, it needs a reference to it. But I want to use this BitAccessor many places, with just a reference to the desired integer.
推荐答案
你不能像那样直接存储对整数的引用,但你可以存储对 GlorifiedInt 的引用
包含它的对象.在您的情况下,我可能会做的是将 BitAccessor
类嵌套在 GlorifiedInt
中(以便它可以访问私有字段),然后将其传递给this
创建后,它可以用来访问 m_val
字段.这是一个可以满足您要求的示例:
You can't store a reference to an integer like that directly, but you can store a reference to the GlorifiedInt
object containing it. In your case, what I'd probably do is make the BitAccessor
class nested inside GlorifiedInt
(so that it gets access to private fields), and then pass it a reference to this
when it's created, which it can then use to access the m_val
field. Here's an example which does what you're looking for:
class Program
{
static void Main(string[] args)
{
var g = new GlorifiedInt(7);
g.Bits[0] = false;
Console.WriteLine(g.Value); // prints "6"
}
}
class GlorifiedInt
{
private int m_val;
public GlorifiedInt(int value)
{
m_val = value;
}
public int Value
{
get { return m_val; }
}
public BitAccessor Bits
{
get { return new BitAccessor(this); }
}
public class BitAccessor
{
private GlorifiedInt gi;
public BitAccessor(GlorifiedInt glorified)
{
gi = glorified;
}
public bool this[int index]
{
get
{
if (index < 0 || index > 31)
throw new IndexOutOfRangeException("BitAcessor");
return (1 & (gi.m_val >> index)) == 1;
}
set
{
if (index < 0 || index > 31)
throw new IndexOutOfRangeException("BitAcessor");
if (value)
gi.m_val |= 1 << index;
else
gi.m_val &= ~(1 << index);
}
}
}
}
这篇关于如何在 C# 中存储对整数的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!