【发布时间】:2019-07-31 20:35:32
【问题描述】:
最近我尝试在泛型方法中访问静态列表,但尝试这样做时收到错误。有没有办法在泛型方法中访问静态变量,或者这是不允许的?如果不允许,您介意解释一下原因和可能的解决方法吗?
class Parent
{
public static List<Parent> staticList = new List<Parent>();
public Parent()
{
staticList.Add(this);
}
public static void RemoveItemFromList<T>() where T: Parent, new()
{
//This throws an error
T.staticList.RemoveAt(0);
}
}
class Child : Parent
{
public Child()
{
staticList.Add(this);
}
}
当我将鼠标悬停在
T.staticList.RemoveAt(0)
(以红色突出显示)它声明:“'T' 是一个类型参数,在给定的上下文中无效”。
编辑:
很抱歉让您感到困惑。这是修改后的代码sn-p:
我怎样才能让它工作(不使列表非静态,同时保持方法通用):
class Parent
{
public static List<Parent> staticList = new List<Parent>();
public static void AGenericMethod<T>() where T: Parent
{
Console.WriteLine(T.staticList[0]);
// This throws an error.
// 'T' is a type parameter, which is not valid in the given context.
}
}
class Child : Parent
{
public static new List<Parent> staticList = new List<Parent>();
}
【问题讨论】:
-
你为什么不直接做
staticList.RemoveAt(0)?静态列表总是在Parent上定义。如果您需要在孩子中使用不同的列表,那么它不应该是静态的。
标签: c# list oop generics static