c# - 是否可以在泛型方法 (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>();
}
解决方案
我认为您尝试使用 T 在Parent.staticList
and之间交换Child.staticList
。
据我所知,静态原则上永远不会受到类继承的影响。从来没有静态的Child.staticList
。它总是在访问 Parent.StaticList。
我知道只有一种方法可以通过继承影响静态 - 如果静态调用实例函数。我能想到的唯一例子是Equals。在进行一些与参考相关public static bool Equals (object objA, object objB);
的检查后将调用 objA 。public virtual bool Equals (object obj);
请注意,您可以定义静态属性。属性主要(但不完全)是 get/set 函数对的语法糖。
推荐阅读
- python - Django:无法在管理面板中注册模型
- spring - Thymeleaf 片段内容不替换主要内容?
- python - 制作一个刷新按钮
- javascript - Node.js - TypeError: res.json is not a function(在某些路由中工作而不在其他路由中工作)
- javascript - 如何打开一个新窗口(音乐播放器)并将其托管在 Shopify 环境中
- python - 使用 API 进行身份验证扫描的有效 OWASP Zap 脚本示例
- tabs - 带有子选项卡的 Flutter Appbar(操作)
- android - 打开特定的文件扩展名
- javascript - 将类添加到引导轮播项目
- amazon-web-services - 我可以使用 Rancher HA 设置执行滚动升级吗