首页 > 解决方案 > 是否可以在泛型方法 (C#) 中访问静态成员变量?

问题描述

最近我尝试在通用方法中访问静态列表,但在尝试这样做时收到错误。有没有办法在泛型方法中访问静态变量,或者这是不允许的?如果不允许,您是否介意解释原因和可能的解决方法。

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' 是一个类型参数,在给定的上下文中无效”。

编辑:

很抱歉造成混乱。这是修改后的代码片段:

我怎样才能让它工作(不使列表非静态,同时保持方法通用):

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>();
}

标签: c#listoopgenericsstatic

解决方案


我认为您尝试使用 T 在Parent.staticListand之间交换Child.staticList

据我所知,静态原则上永远不会受到类继承的影响。从来没有静态Child.staticList。它总是在访问 Parent.StaticList。

我知道只有一种方法可以通过继承影响静态 - 如果静态调用实例函数。我能想到的唯一例子是Equals。在进行一些与参考相关public static bool Equals (object objA, object objB);的检查后将调用 objA 。public virtual bool Equals (object obj);

请注意,您可以定义静态属性。属性主要(但不完全)是 get/set 函数对的语法糖。


推荐阅读