質問

I'm updating a method that contains an out parameter. I need to check the value of the parameter before setting it to a default.

public int DoWork(out int param)
{
    param = 0;
}

However, when I try to do something like this

public int DoWork(out int param)
{
    if(param == 8)
        param = 0;
}

I get an error saying "Use of unassigned out parameter 'param'".

Is there a way I can use the value passed to the method before assigning it?

UPDATE: I cannot use the ref keyword. A lot of code would break and it's not part of the design

役に立ちましたか?

解決

You can if you really need and want to cheat. Here's the sample code:

using System;
using System.Reflection.Emit;

namespace Test774
{
    class MainClass
    {
        public static void Main(string[] args)
        {
            var a = 666;
            DoWork(out a);
        }

        public static int DoWork(out int param)
        {
            var dynamicMethod = new DynamicMethod("ParameterExtractor", typeof(int), new [] { typeof(int).MakeByRefType() });
            var generator = dynamicMethod.GetILGenerator();
            generator.Emit(OpCodes.Ldarg_0);
            generator.Emit(OpCodes.Ldind_I4);
            generator.Emit(OpCodes.Ret);
            var parameterExtractor = (MethodWithTheOutParameter)dynamicMethod.CreateDelegate(typeof(MethodWithTheOutParameter), null);
            Console.WriteLine(parameterExtractor(out param));
            param = 1;
            return 0;
        }

        public delegate int MethodWithTheOutParameter(out int a);
    }
}

他のヒント

You can use ref keyword.

public int DoWork(ref int param)
{
    if(param == 8)
        param = 0;
}

This way you can assign a new value to your param but also use the old one. Take a look at http://msdn.microsoft.com/en-us//library/14akc2c7.aspx

You should use "ref" keyword instead of "out".

"Out" specifically means that the parameter is initialized and assigned in the method, with no need to initalize it before, and so compiler assume that the parameter is just declared but has no value.

"Ref", instead, does exactly what you are looking for.

public int DoWork(ref int param)
{
    if(param == 8)
        param = 0;
}

//your code:
int val = 5;
DoWork(ref val);
val.ToString(); // outputs 5
val = 8;
DoWork(ref val);
val.ToString(); // outputs 0

Is there a way I can use the value passed to the method before assigning it?

No, there isn't, and it does not have a value anyway (either zero or garbage).

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top