简体   繁体   English

检查int在范围内时,无法将void转换为int

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

I'm using this code and it's giving me an error saying that it cannot convert void to int: 我正在使用此代码,它给我一个错误,指出它无法将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}]");
        }
    }

Can anyone see what's wrong and why it's giving this error? 谁能看到问题所在以及为什么会出现此错误?

You will need to return the value if it's not out of range. 如果该值不在范围内,则需要返回该值。 Otherwise the set doesn't receive an int. 否则,该集合将不接收整数。
So simply add return value; 因此,只需添加return value; after your if and you should be good. 在你之后,如果你应该很好。

Edit: and of course change the return type from void to int. 编辑:当然将返回类型从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