ReSharper的警告说:"在泛型类型和QUOT静态字段; [英] ReSharper warns: "Static field in generic type"

查看:149
本文介绍了ReSharper的警告说:"在泛型类型和QUOT静态字段;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class EnumRouteConstraint<T> : IRouteConstraint
    where T : struct
{
    private static readonly Lazy<HashSet<string>> _enumNames; // <--

    static EnumRouteConstraint()
    {
        if (!typeof(T).IsEnum)
        {
            throw new ArgumentException(Resources.Error.EnumRouteConstraint.FormatWith(typeof(T).FullName));
        }

        string[] names = Enum.GetNames(typeof(T));
        _enumNames = new Lazy<HashSet<string>>(() => new HashSet<string>
        (
            names.Select(name => name), StringComparer.InvariantCultureIgnoreCase
        ));
    }

    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
    {
        bool match = _enumNames.Value.Contains(values[parameterName].ToString());
        return match;
    }
}

这是错的?我会认为这实际上有一个静态只读字段为每个可能的 EnumRouteConstraint&LT; T&GT; ,我碰巧实例。

Is this wrong? I would assume that this actually has a static readonly field for each of the possible EnumRouteConstraint<T> that I happen to instance.

推荐答案

它的优良有一个静态字段泛型类型,只要你知道你会真正得到每个类型参数组合一个字段。我的猜测是,R·只是警告你如果你没有意识到这一点。

It's fine to have a static field in a generic type, so long as you know that you'll really get one field per combination of type arguments. My guess is that R# is just warning you in case you weren't aware of that.

下面是这样一个例子:

using System;

public class Generic<T>
{
    // Of course we wouldn't normally have public fields, but...
    public static int Foo;
}

public class Test
{
    public static void Main()
    {
        Generic<string>.Foo = 20;
        Generic<object>.Foo = 10;
        Console.WriteLine(Generic<string>.Foo); // 20
    }
}

正如你所看到的,通用&LT;串&GT;包含.foo 是从不同的领域通用&LT;对象&gt;包含.foo - 他们持有不同的价值观

As you can see, Generic<string>.Foo is a different field from Generic<object>.Foo - they hold separate values.

这篇关于ReSharper的警告说:&QUOT;在泛型类型和QUOT静态字段;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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