这里已经有几个很好的答案,可以解释警告及其原因。其中一些状态类似于在泛型类型中具有静态字段通常是一个错误。
我想我会添加一个示例来说明此功能如何有用,即抑制 R# 警告是有意义的情况。
假设您有一组要序列化的实体类,例如 Xml。您可以使用new XmlSerializerFactory().CreateSerializer(typeof(SomeClass)) 为此创建一个序列化程序,但是您必须为每种类型创建一个单独的序列化程序。使用泛型,您可以将其替换为以下内容,您可以将其放在可以派生实体的泛型类中:
new XmlSerializerFactory().CreateSerializer(typeof(T))
由于您可能不希望每次需要序列化特定类型的实例时都生成新的序列化程序,因此您可以添加以下内容:
public class SerializableEntity<T>
{
// ReSharper disable once StaticMemberInGenericType
private static XmlSerializer _typeSpecificSerializer;
private static XmlSerializer TypeSpecificSerializer
{
get
{
// Only create an instance the first time. In practice,
// that will mean once for each variation of T that is used,
// as each will cause a new class to be created.
if ((_typeSpecificSerializer == null))
{
_typeSpecificSerializer =
new XmlSerializerFactory().CreateSerializer(typeof(T));
}
return _typeSpecificSerializer;
}
}
public virtual string Serialize()
{
// .... prepare for serializing...
// Access _typeSpecificSerializer via the property,
// and call the Serialize method, which depends on
// the specific type T of "this":
TypeSpecificSerializer.Serialize(xmlWriter, this);
}
}
如果这个类不是通用的,那么这个类的每个实例都将使用相同的_typeSpecificSerializer。
由于它是通用的,但是对于 T 具有相同类型的一组实例将共享 _typeSpecificSerializer 的单个实例(将为该特定类型创建),而对于 @ 具有不同类型的实例987654327@ 将使用_typeSpecificSerializer 的不同实例。
一个例子
提供了扩展SerializableEntity<T>的两个类:
// Note that T is MyFirstEntity
public class MyFirstEntity : SerializableEntity<MyFirstEntity>
{
public string SomeValue { get; set; }
}
// Note that T is OtherEntity
public class OtherEntity : SerializableEntity<OtherEntity >
{
public int OtherValue { get; set; }
}
...让我们使用它们:
var firstInst = new MyFirstEntity{ SomeValue = "Foo" };
var secondInst = new MyFirstEntity{ SomeValue = "Bar" };
var thirdInst = new OtherEntity { OtherValue = 123 };
var fourthInst = new OtherEntity { OtherValue = 456 };
var xmlData1 = firstInst.Serialize();
var xmlData2 = secondInst.Serialize();
var xmlData3 = thirdInst.Serialize();
var xmlData4 = fourthInst.Serialize();
在这种情况下,在后台,firstInst 和 secondInst 将是同一类的实例(即SerializableEntity<MyFirstEntity>),因此,它们将共享_typeSpecificSerializer 的实例。
thirdInst 和 fourthInst 是不同类 (SerializableEntity<OtherEntity>) 的实例,因此将共享一个与其他两个不同的 _typeSpecificSerializer 实例。
这意味着您可以为每个实体类型获得不同的序列化程序实例,同时在每个实际类型的上下文中仍然保持它们静态(即,在特定类型的实例之间共享) .