ReSharper 警告:“泛型类型中的静态字段" [英] ReSharper warns: "Static field in generic type"
本文介绍了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
.
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
}
}
如您所见,Generic
与 Generic
是不同的字段 - 它们保存不同的值.
As you can see, Generic<string>.Foo
is a different field from Generic<object>.Foo
- they hold separate values.
这篇关于ReSharper 警告:“泛型类型中的静态字段"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文