就我而言,我有一堆相同类型的值,比如说floats:
float value1 = 1.2f;
float value2 = 1.5f;
float value3 = 2.3f;
现在我需要一个指针或参考值来获取这个浮点数的实例并对其进行操作。
在 C++ 中:
float* float_reference;
现在我想value1
在我的函数中将 float_reference 设置为 So,每次计算都将结果放入 value1。
注意: - 我不想使用类 - 我不想在函数中使用 ref 关键字 - 我不想使用 unsafe 关键字
我只需要像我说的那样做 C++,还有其他方法吗?
编辑 1:这就是我不能使用 unsafe 的原因,下面是示例:
using System.Windows;
namespace ValueUpdater
{
public unsafe partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
//// need to assign one of floats to reference object
}
float value1 = 1.2f;
float value2 = 1.5f;
float value3 = 2.3f;
float* value_ref; ////// Can't Make this pointer!
private void Button_Click(object sender, RoutedEventArgs e)
{
/// Need to change the reference here
fixed (float* value_ref = &value3) {
*value_ref += 2;
};
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
/// Need to change the reference here
/// But can't use value_ref = &value3 without re-initalize
fixed (float* value_ref = &value3)
{
*value_ref -= 2;
};
}
private void Button_Click_2(object sender, RoutedEventArgs e)
{
Output.Content = value3.ToString();
}
}
}
XAML:
<Window x:Class="ValueUpdater.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:ValueUpdater"
mc:Ignorable="d"
Title="MainWindow" Height="354.017" Width="368.698">
<Grid>
<Button Content="Add 2" Margin="0,28,27,0" VerticalAlignment="Top" HorizontalAlignment="Right" Width="75" Click="Button_Click"/>
<Button Content="Sub 2" Margin="0,55,27,0" VerticalAlignment="Top" HorizontalAlignment="Right" Width="75" Click="Button_Click_1"/>
<Button Content="Reset" Margin="0,83,27,0" VerticalAlignment="Top" HorizontalAlignment="Right" Width="75"/>
<Button Content="Print" Margin="0,0,27,20" HorizontalAlignment="Right" Width="75" Height="20" VerticalAlignment="Bottom" Click="Button_Click_2"/>
<Label x:Name="Output" Content="Output" HorizontalAlignment="Left" Margin="19,22,0,0" VerticalAlignment="Top" Width="182"/>
</Grid>
</Window>