如果不使用返回值,是否有可能得到警告? [英] Is it possible to get a warning if return value is not used?

查看:38
本文介绍了如果不使用返回值,是否有可能得到警告?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个扩展方法,它返回一个值.在这种情况下,应在字节中设置一个特定位:

I have an extension method which returns a value. In this case, it should set a specific bit in a byte:

public static byte SetBit(this byte b, int bitNumber, bool value)
{
    if (value)
    {
        return (byte)(b | (1 << bitNumber));
    }
    return (byte)(b & ~(1 << bitNumber));
}

返回的值需要再次分配给变量,因为我不能组合 this ref :

The returned value needs to be assigned to a variable again, because I cannot combine this and ref:

byte myByte = 3;
myByte = myByte.SetBit(1, false);

很容易意外忘记分配.可能有人认为该方法直接更改了值.

It is easy to forget the assignment by accident. Someone might think that the method changes the value directly.

对于 String.Replace ,ReSharper/Visual Studio (?)警告我未使用纯方法的返回值:

For a String.Replace, ReSharper/Visual Studio(?) is warning me that the Return value of pure method is not used:

在某种程度上我的方法也可以吗?

Is this also possible for my method in some way?

推荐答案

似乎为这包括 MustUseReturnValueAttribute :

[MustUseReturnValue("Use the return value to...")]
public byte Foo()
{    
}

正如@Kirk Woll在评论中指出的,也可以编写自定义

As @Kirk Woll pointed out in the comments, it is also possible to write a custom Roslyn Analyzer.

这篇关于如果不使用返回值,是否有可能得到警告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆