簡體   English   中英

檢查int在范圍內時,無法將void轉換為int

[英]Cannot convert void to int when checking an int is within a range

我正在使用此代碼,它給我一個錯誤,指出它無法將void轉換為int:

    private static int aBtn;
    public static int ABtn
    {
        get => aBtn;
        set => aBtn = CheckArgumentRange(nameof(value), value, 0, 5);
    }

    internal static void CheckArgumentRange(
        string paramName, int value, int minInclusive, int maxInclusive)
    {
        if (value < minInclusive || value > maxInclusive)
        {
            throw new ArgumentOutOfRangeException(paramName, value,
                $"Value should be in range [{minInclusive}-{maxInclusive}]");
        }
    }

誰能看到問題所在以及為什么會出現此錯誤?

如果該值不在范圍內,則需要返回該值。 否則,該集合將不接收整數。
因此,只需添加return value; 在你之后,如果你應該很好。

編輯:當然將返回類型從void更改為int。

    private static int aBtn;
    public static int ABtn
    {
        get => aBtn;
        set => aBtn = CheckArgumentRange(nameof(value), value, 0, 5);
    }

    internal static int CheckArgumentRange(
        string paramName, int value, int minInclusive, int maxInclusive)
    {
        if (value < minInclusive || value > maxInclusive)
        {
            throw new ArgumentOutOfRangeException(paramName, value,
                $"Value should be in range [{minInclusive}-{maxInclusive}]");
        }

        return value;
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM