本文介绍了无法通过基本类型的变量作为输出参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只注意到这不起作用:

  VAR字典=新词典< INT,的XElement>(); 
XContainer元素;
// ...
如果(dict.TryGetValue(IDX,出元素)){// ...

然后我尝试这样的:

 类A {} 
b类: A {}

类节目{
静态无效的主要(){
A A;
A =惩戒(); //没有错误,确定
参考(REF A); //编译器错误,确定...
OUT(出); //编译器错误,lolwut?
}
静态乙惩戒(){返回NULL; }
静态无效的参考(REF B B){}
静态无效输出(输出B B){B = NULL; }
}



我为什么会在最后一次调用编译器错误?



修改确定,所以当我从答案出理解为变相的裁判,因此它可以共享和其它功能改变或线程。不过说真的,是不是'出来'应该是从一个函数返回多个值的方法吗?因为如果是这样,它似乎并不擅长的。 如果共享产生的问题,那么不共享。只要创建在函数的开始一个隐藏的变量,并使用它。我的意思是:



 静态无效输出(输出B B){$ B $条b B bHidden; //编译器生成; 
//所有到B的引用将被替换为bHidden;
B = bHidden;
}

是否有任何理由不能做到这样?现在看来安全,我...


解决方案
static void Out(out B b)
{
    B bHidden; // compiler generated;
               // all references to b are replaced with bHidden;
    b = bHidden;
}

Such a system is called a "copy out" system, for obvious reasons. It could be done that way, but doing so creates interesting problems of its own. For example:

void M()
{
    int b = 1;
    try
    {
        N(out b);
    }
    catch (FooException)
    {
        Console.WriteLine(b);
    }
}

void N(out int c)
{
    c = 123;
    P();
    c = 456;
}

void P()
{
    throw new FooException();
}

What is the output of the program? What should it be?

Next problem: Do you want out's behaviour to be consistent or inconsistent with ref? If you want it to be inconsistent, then congratulations, you just added a highly confusing inconsistency to the language. If you want it to be consistent then you need to make ref use "copy in copy out" semantics, which introduces a number of problems of its own, both in terms of performance and in terms of correctness.

I could go on all day enumerating the differences between reference semantics and copy semantics, but I won't. The system we've got is the system we've got, so learn to work with it.

And besides, if you want to return more than one value from a method, don't use an out parameter. That might have been the smart thing to do in 2001, but it is 2012 now and we have more tools at your disposal. If you want to return two values:

  • return a tuple
  • refactor the code into two methods that each return one value
  • if the two values are a value type and a bool, return a nullable value type.

这篇关于无法通过基本类型的变量作为输出参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 06:07