使用非字符串作为字符串(而不是自动使用ToString)时,如何显示错误? [英] How to get an error shown when using non strings as strings (instead of an automatic use of ToString)?

查看:39
本文介绍了使用非字符串作为字符串(而不是自动使用ToString)时,如何显示错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

建议的重复确实是一个类似的问题.但是,那里的答案仅涉及一个选项-禁用ToString()本身.还有其他可能的解决方案,例如让Visual Studio警告我,或者不调用ToString()(仔细阅读答案,他假设调用了 ,并仅说明存在不能删除" ToString().),或使用较低版本的C#(它是否始终以这种方式工作?),等等.

当我在代码中期望使用字符串的某个地方有一个非字符串时,我不希望它自动转换为字符串.我想要一个错误.例如:

 公共字符串Stringify(){返回数据+ Environment.NewLine;} 

数据是一个我不想获取的 byte [] :

System.Byte []

我想得到一个错误,所以我知道我需要修复它.(有理由要强打字.)

所以,有一种方法可以使Visual Studio/C#/.Net在使用非字符串作为字符串时向我显示错误/抛出异常?

解决方案

可以在Visual Studio 2017中使用Nuget在您的项目中安装Rosyln分析器.

特别是有一个Rosyln分析器,如果在类中未覆盖 ToString(),则检查对 ToString()的隐式和显式调用.

默认情况下,此分析器将产生警告,如带有的三角形所示.但是,右键单击规则,您可以将任何规则提升为错误,或将其简化为提供信息.

可能的陷阱

Console.Write Console.WriteLine 具有多个重载,包括 Console.Write(object value),因此,如果要打印某些对象未覆盖 ToString()之类的 Console.Write(myCustomObject)的分析器将不会捕获此信息,因为没有进行隐式转换(至少在代码中您已经写过)

The suggested duplicate is indeed a similar question. However, the answer there covers only one option - disabling the ToString() itself. There are other possible solutions such as having Visual Studio warn me about it, or have the ToString() not be called (read the answer there carefully, he assumes it is called, and just explains that there is no way of "removing" ToString().), or use a lower version of C# (did it always work this way?), etc...

When I have a non string somewhere where a string is expected by the code I don't want it automatically converted to string. I want an error. For example:

public string Stringify()
{
    return Data + Environment.NewLine;
}

And Data is a byte[] I DON'T want to get:

System.Byte[]

I want to get an error so I know I need to fix it. (There's a reason for strong typing.)

So, is there a way to get Visual-Studio/C#/.Net to show me an error/throw-an-Exception when using non strings as strings?

解决方案

Rosyln analyzers can be installed in your project using Nuget in Visual Studio 2017.

In particular there is a Rosyln analyzer that checks for implicit and explicit calls to ToString() if ToString() is not overridden in the class. https://www.nuget.org/packages/ToStringWithoutOverrideAnalyzer/

Installed analyzers can be found under references

By default this analyzer will produce warnings as shown by the triangle with !, but right clicking on the rules you can elevate any rule to be an error, or reduce it to informational.

Potential gotcha

Console.Write and Console.WriteLine have several overloads including Console.Write(object value), so if you are printing some object that hasn't overridden ToString() like Console.Write(myCustomObject) the analyzer will not catch this because there is no implicit conversion being made (at least in the code that you have written)

这篇关于使用非字符串作为字符串(而不是自动使用ToString)时,如何显示错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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