Reference to var c#
本文关键字:var to Reference | 更新日期: 2023-09-27 18:03:01
我想知道是否有一种方法可以使用var的引用,如'ref',但不是在方法中。例:
using System;
using System.Collections;
using System.Collections.Generic;
public class Class3
{
struct myStruct
{
public bool structBool;
public int structInt;
public myStruct(bool _structBool, int _structInt)
{
structBool = _structBool;
structInt = _structInt;
}
}
myStruct currentTask;
int value1,value2;
bool mybool, isProcessing;
Queue<myStruct> myTask = new Queue<myStruct>();
void main()
{
//these two lines don't work due to the "ref" but I'm looking for something work like this
if (value1 > value2) myTask.Enqueue(new myStruct(mybool,ref value1));
if (value2 > value1) myTask.Enqueue(new myStruct(mybool,ref value2));
MyFunction();
}
void MyFunction()
{
if (myTask.Count > 0)
{
if (!isProcessing)
{
currentTask = myTask.Dequeue();
isProcessing = true;
}
else
{
currentTask.structInt++; // here I need to catch my var (value1 or value2)
}
}
}
}
我试图把值放入数组,但我认为这是一个坏的方式。我尝试了很多其他的东西,但没有一个正常工作
您可以更改构造函数以通过引用传递这些参数,如下所示:
public myStruct(bool _structBool, ref int _structInt)
,
currentTask.structInt++;
仍然不会改变原来的变量(value1
, value2
)。查看答案中的解决方案:https://stackoverflow.com/a/13120988/775018
通常当你想给构造函数(甚至是一个方法)提供多个值时,将它们作为类的一部分提供是非常可以接受的:
public class Args
{
public int Value { get; set; }
}
现在你可以这样写:
Args args1 = new Args { Value = 10 };
Args args2 = new Args { Value = 34 };
// Obviously, your structs or classes should accept Args class as input parameter
var struct1 = new MyStruct(true, args1);
var struct2 = new MyStruct(false, args2);
现在对Args.Value1
和/或Args.Value2
的修改将对结构构造函数调用者可用。