【问题标题】:Name Can Be Simplified - Visual Studio 2019 Override [duplicate]名称可以简化 - Visual Studio 2019 覆盖 [重复]
【发布时间】:2020-12-17 00:04:55
【问题描述】:

我的 ASP.NET 项目中有以下代码行:

    public virtual async Task<bool> Delete(int id)
    {
        var entity = LoadById(id);
        using (IDbConnection cn = new SqlConnection(_conn))
        {
            cn.Open();
            /* Do Not Remove <T> Variables, its required even though the compiler notes its not required */
            var result = await cn.DeleteAsync<T>(entity);

            return result;
        }
    }

这是类定义:

public abstract class DatabaseRepository<T> where T : class, IDatabaseModel, new()

Visual Studio 2019 显示一条警告,提示我需要从 DeleteAsync 方法中删除 T 变量,因为它不需要并且可以简化。问题是我正在使用的扩展(Dapper)需要它。一旦我删除 T 引用,我的代码就会抛出运行时异常。

发件人:

var result = await cn.DeleteAsync<T>(entity);

收件人:

var result = await cn.DeleteAsync(entity);

我的第一个想法是在此行旁边添加注释以防止其他开发人员将其删除。但是,我开始考虑必须在代码中进行某种类型的覆盖,以防止它显示为警告。某种类型的特殊注释或我可以放在行上方以防止视觉工作室显示消息的东西。到目前为止,我在网上查过,找不到任何东西。我正在寻找可以放入代码中的东西,而不是 Visual Studio 中的设置更改。

【问题讨论】:

  • 它是否在消费者电话中发出警告?可能是因为编译器可以根据实体的类型来推断类型,所以泛型调用的类型注解是多余的。
  • LoadById返回的类型是什么?
  • 如果您阅读了答案,您会看到您可以禁用仅一行的警告。
  • 去掉泛型类型参数时,是不是调用了object predicate参数而不是T entity参数的扩展方法?
  • 你得到什么样的警告? Intellisense、编译、FxCop 还有什么?

标签: c# asp.net visual-studio visual-studio-2019


【解决方案1】:

不要添加评论,而是添加SuppressMessage,这将首先阻止警告。

[SuppressMessage("Reason", "Whatever the id is", Justification="Do Not Remove <T> Variables, its required even though the compiler notes its not required")]
public virtual async Task<bool> Delete(int id)
{
    var entity = LoadById(id);
    using (IDbConnection cn = new SqlConnection(_conn))
    {
        cn.Open();
        var result = await cn.DeleteAsync<T>(entity);

        return result;
    }
}

【讨论】:

  • 试过了,这个不行:(
  • 怎么没用?编译器错误?你到底在属性中放了什么?
  • 没关系,我的 ID 错误,这有效:[SuppressMessage("Reason", "IDE0001", Justification = "Do Not Remove 变量,即使编译器指出它不是,它也是必需的必填")]
猜你喜欢
  • 2020-12-05
  • 1970-01-01
  • 1970-01-01
  • 2021-05-13
  • 2015-10-20
  • 2018-07-29
  • 1970-01-01
  • 2016-09-07
  • 1970-01-01
相关资源
最近更新 更多