【问题标题】:c# out causing a no overload for method error?c# out 导致方法错误没有重载?
【发布时间】:2019-07-31 17:11:15
【问题描述】:

我是 C# 新手,对 out 参数修饰符的工作原理有点困惑。

我有这个功能

public static void GuidUnsmash(string smashed, out Guid first, out Guid second)
{
    if (smashed.Length != 64)
    {
        throw new ArgumentOutOfRangeException();
    }

    string firstGuid = smashed.Substring(0, 32);
    string secondGuid = smashed.Substring(32, 32);

    first = new System.Guid(firstGuid);
    second = new System.Guid(secondGuid);
}

我试图用这个来调用它

[HttpGet]
public async Task<ActionResult> Pending(string pendingticket)
{
    // CAR-AAR built with PersonId and MonerisID in ticket, this was overkill, just needed the MonerisID
    GuidHelpers.GuidUnsmash(pendingticket, out Guid personId, out Guid monerisId); //this is the line that has the error
    var preload = await MonerisApplicationRepository.PrepareTransactionForMonerisPreload(monerisId);
    var preloadResponse = await MonerisRepository.PostPreloadTransactionRequest(preload);
    var persistPreload = await MonerisApplicationRepository.PersistMonerisPreloadTransactionResponse(monerisId, preloadResponse);

    var transactionRequest = preloadResponse.ToMonerisPreAuthorization();

    //var viewPendingRequest = new MonerisPendingPreloadTransaction(transactionRequest, preload);

    // View redirects to Moneris with autosubmit to begin preauthorization process.
    return View(transactionRequest);
}

但是我收到一个错误,提示 GuidUnsmash 没有重载方法。这让我很困惑,因为它们都有相同数量的参数。

【问题讨论】:

  • 请提供minimal reproducible example,以便我们重现问题。确保包含确切错误消息。
  • @RufusL @Christopher 您可以在方法调用docs.microsoft.com/en-us/dotnet/csharp/whats-new/… 中内联out 变量声明
  • 任何时候您“遇到错误”都需要告诉我们错误是什么。
  • 你的方法编译并可以调用。 ideone.com/5UNthu该错误是由您未在问题中显示的代码引起的。
  • 在描述特定错误或异常时,请按原样剪切并粘贴实际错误消息。自己解释错误可能会引起很多混乱,而原始错误消息通常是可搜索的。

标签: c# guid out


【解决方案1】:

通常,函数调用中使用的参数是“按值传递”。另一个选项是通过引用传递参数。

关键字ref 强制参数通过引用传递。但这并不意味着该函数实际上会对变量做任何事情。可能会也可能不会。

关键字out 强制参数通过引用传递,并且值必须在函数中分配。这可能对需要赋值的readonly 变量产生影响。所以调用者知道这个值不会保持不变。

关键字in 是相对较新的语法,与'ref' 和'out' 有关。它强制参数通过引用传递,但也防止对值进行任何重新分配(如倒置的out)。但是我有点不确定你为什么要使用它。

在使用裸指针的语言中,通常使用裸指针代替ref。并且没有inout 关键字。

至于重载:

inrefout 关键字不被视为 用于重载解析的方法签名。所以, 如果唯一的区别是一种方法,则方法不能重载 采用refin 参数,另一个采用out 参数。

这意味着错误没有真正的意义。

这样就留下了一个难以调试的问题:代码在这两个代码之前或之间的某个地方被破坏了,编译器有问题,甚至仍然告诉你错误在哪里。

【讨论】:

  • 这是一个有效的函数调用。 docs.microsoft.com/en-us/dotnet/csharp/whats-new/…
  • @dee-see 啊。好的,固定
  • 你的 out vs ref 是很好的信息。
  • 我打赌在某个地方还有另一个 GuidUnsmash 导致了错误。
  • @JoshuaRobinson:这个优化级别通常是我会留给 JiT 的,但我找到了一个我认为的原因:In 确实需要初始化变量。所以我想说的用途是围绕那些简短的空检查语法。
猜你喜欢
  • 2015-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-07
  • 1970-01-01
  • 2012-09-24
  • 1970-01-01
  • 2011-05-15
相关资源
最近更新 更多