代码分析警告与泛型方法CA1004

代码分析警告与泛型方法CA1004

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

问题描述

我有以下的泛型方法:

// Load an object from the disk
public static T DeserializeObject<T>(String filename) where T : class
{
    XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));

    try
    {
        TextReader textReader = new StreamReader(filename);
        var result = (T)xmlSerializer.Deserialize(textReader);
        textReader.Close();
        return result;
    }
    catch (FileNotFoundException)
    { }

    return null;
}

当我编译,我得到以下警告:结果
CA1004:Microsoft.Design:考虑一个设计,其中MiscHelpers.DeserializeObject(字符串)不给它任何调用需要显式类型参数'T'

When I compile I get the following warning:
CA1004 : Microsoft.Design : Consider a design where 'MiscHelpers.DeserializeObject(string)' doesn't require explicit type parameter 'T' in any call to it.

我已经考虑过这一点,我不知道的方式做它用了限制可反序列化类型的请求。我坦率地承认,我可能会丢失一个简单的方法来解决这个问题。

I have considered this and I don't know a way to do what it requests with out limiting the types that can be deserialized. I freely admit that I might be missing an easy way to fix this.

但是,如果我没有,那么我要禁止这种警告唯一的办法?我有一个干净的项目,没有警告或消息。我想保持这种方式。

But if I am not, then is my only recourse to suppress this warning? I have a clean project with no warnings or messages. I would like to keep it that way.

我想我问:为什么这是一个警告?在最好的情况,这似乎像它应该是一个消息。即使这似乎有点多。或者它可以或可以不固定。如果能,那么你只是坚持不与没有办法,只能抑制它的警告。难道我错了吗?

I guess I am asking "why this is a warning?" At best this seems like it should be a message. And even that seems a bit much. Either it can or it can't be fixed. If it can't then you are just stuck with the warning with no recourse but suppressing it. Am I wrong?

推荐答案

由于您使用 T 在返回类型,这是一个假阳性。

Since you're using T in the return type, this is a false positive.

据固定在代码分析VS2010。

It was fixed in Code Analysis for VS2010.

这篇关于代码分析警告与泛型方法CA1004的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 20:01