ReSharper が警告: ​​「ジェネリック型の静的フィールド」 質問する

ReSharper が警告: ​​「ジェネリック型の静的フィールド」 質問する
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;
    }
}

これは間違っていますか? 実際には、インスタンス化するstatic readonly可能性のあるものごとにフィールドがあると思います。EnumRouteConstraint<T>

ベストアンサー1

型引数の組み合わせごとに 1 つのフィールドが実際に取得されることがわかっている限り、ジェネリック型に静的フィールドがあっても問題ありません。私の推測では、R# は、ユーザーがそれに気付いていない場合に警告しているだけだと思います。

次にその例を示します。

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

ご覧のとおり、Generic<string>.Fooは とは異なるフィールドでありGeneric<object>.Foo、別々の値を保持します。

おすすめ記事