C# pointer reference
Is there a way to create c++ style pointer in c#? I need this to set an int in several places when I don't know which int it is.
Like in c++ I would do:int *i;
if(cond0) 开发者_如何学Goi = &someint;
if(cond1) i = &otherint;
if(cond2) i = &thirdint;
if(cond3) *i = someval;
if(cond4) *i = otherval;
if(cond5) *i = thirdval;
If I do this in c# style I will need 9 ifs and my program has much more conditions so its not feasible.
I thought of make some sort of value like:int val;
if(cond3) val = someval;
if(cond4) val = otherval;
if(cond5) val = thirdval;
if(cond0) someint = val;
if(cond1) otherint = val;
if(cond2) thirdint = val;
but it's not possible because cond3, 4 and 5 are scattered along the program.
It is, but you have to wrap any code that does it in an unsafe block.
Alternatively, if this is happening in a method then you might be able to use the 'ref' keyword to pass a parameter in by reference.
Both of these options really constrain the solution to method boundaries. If you're dealing with anything more scattered than that, in C# it's probably better to try and find ways to reorganize your code to use less global state instead.
Yes, there is a type called IntPtr which I use for Windows handles.
Here's an example of C# pointers that illustrates both their declaration and how to wrap them in an unsafe block
Also, see the C# Programming Guide - Pointer Types
I'm not sure if you provided enough information in your question to give a correct answer, but one possible solution is to set the values in a function using ref parameters.
class Program
{
static void Main(string[] args)
{
var i = 1;
var someint = 2;
var otherint = 3;
var thirdint = 4;
Console.WriteLine("i: {0}\nsomeint: {1}\notherint: {2}\nthirdint: {3}", i, someint, otherint, thirdint);
SetInts(true, false, false, false, false, false, ref i, ref someint, ref otherint, ref thirdint);
Console.WriteLine("i: {0}\nsomeint: {1}\notherint: {2}\nthirdint: {3}", i, someint, otherint, thirdint);
Console.ReadKey();
}
static void SetInts(bool cond0, bool cond1, bool cond2, bool cond3, bool cond4, bool cond5, ref int i, ref int someint, ref int otherint, ref int thirdint)
{
if (cond0) i = someint;
if (cond1) i = otherint;
if (cond2) i = thirdint;
if (cond3) i = someint;
if (cond4) i = otherint;
if (cond5) i = thirdint;
}
}
精彩评论