本文介绍了FxCop的铸造警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我运行的FxCop时收到以下错误:

I get the following error when running FXCop:

CA1800:Microsoft.Performance:
'的obj',一个变量,被转换为输入
'工作'的方法
多次'ProductsController.Details(INT,
INT)。高速缓存中的'为'
运营商或直接投以
消除冗余castclass
指令

代码:

        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);
            }
        }



这有什么错呢?我只能看见一投:工作j =(工作)目标文件

What's wrong with this? I can only see one cast: Job j = (Job) obj.

推荐答案

有只有一个的但也有一个的测试的。所以,你可以替换第一个块:

There's only one cast but there's also a test. So you can replace the first block with:

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



这意味着执行时间试验只需要执行一次,而不是两次。这是一个有点微优化 - 在你的情况下,它会使代码有点混乱,因为你需要:

That means the execution time test only needs to be performed once, instead of twice. It's a bit of a micro-optimisation - and in your case it would make the code a bit messier, as you'd need:

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 实际上是一个工作 ...)

(Or declare and initialize p earlier, which wastes a test if obj is actually a Job...)

这篇关于FxCop的铸造警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-09 15:45