gpt4 book ai didi

c# - FXCop 选角警告

转载 作者:行者123 更新时间:2023-12-01 23:11:52 26 4
gpt4 key购买 nike

运行 FXCop 时出现以下错误:

CA1800 : Microsoft.Performance : 'obj', a variable, is cast to type 'Job' multiple times in method 'ProductsController.Details(int, int)'. Cache the result of the 'as' operator or direct cast in order to eliminate the redundant castclass instruction

代码:

        object obj = repository.GetJobOrPlace(jobId);//Returns  (object) place or (object) product

if (obj != null)
{
if (obj is Job)
{
Job j = (Job) obj;
Debug.WriteLine(j.Title);
}
else if (obj is Place)
{
Place p = (Place) obj;
Debug.WriteLine(p.Title);
}
}

这有什么问题吗?我只能看到一种转换:Job j = (Job) obj。

最佳答案

只有一个 Actor ,但还有一个测试。因此,您可以将第一个 block 替换为:

Job j = obj as Job;
if (j != null)
{
Debug.WriteLine(j.Title);
}

这意味着执行时间测试只需执行一次,而不是两次。这是一种微观优化 - 在您的情况下,它会使代码变得有点困惑,正如您所需要的:

Job j = obj as Job;
if (j != null)
{
Debug.WriteLine(j.Title);
}
else
{
Place p = obj as Place;
if (p != null)
{
Debug.WriteLine(p.Title);
}
}

(或者提前声明并初始化p,如果obj实际上是一个Job,这会浪费测试...)

关于c# - FXCop 选角警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2370142/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com