FXCop casting Warning

痞子三分冷 提交于 2019-12-11 01:29:11

问题


I get the following error when running 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

Code:

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

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


回答1:


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

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



来源:https://stackoverflow.com/questions/2370142/fxcop-casting-warning

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!