The*_*esy 2 c# generics static-members
我有以下代码(一个更复杂项目的简单示例),其中我有一个对象类型列表的静态"主"列表.
如果您单步执行代码,我希望通过构造函数创建第二个referenceManager3类型时,_masterList将包含String和Object列表.但事实并非如此.
我假设这是因为ReferenceManager3的每个实例实际上是不同的类类型,因为泛型类型定义.我认为这是正确的吗?
我怎样才能做到这一点?
class Program
{
static void Main(string[] args)
{
ReferenceManager3<string> StringManager = new ReferenceManager3<string>();
ReferenceManager3<object> IntManager = new ReferenceManager3<object>();
}
}
class ReferenceManager3<T> where T : class //IReferenceTracking
{
// Static list containing a reference to all Typed Lists
static List<IList> _masterList = new List<IList>();
// Object Typed List
private List<T> _list = null;
public ReferenceManager3()
{
// Create the new Typed List
_list = new List<T>();
// Add it to the Static Master List
_masterList.Add(_list); // <<< break here on the second call.
}
}
Run Code Online (Sandbox Code Playgroud)
您可以从非泛型(抽象)基类派生泛型类:
abstract class ReferenceManager3
{
// Static list containing a reference to all Typed Lists
protected static List<IList> _masterList = new List<IList>();
}
class ReferenceManager3<T> : ReferenceManager3 where T : class //IReferenceTracking
{
// Object Typed List
private List<T> _list = null;
public ReferenceManager3()
{
// Create the new Typed List
_list = new List<T>();
// Add it to the Static Master List
_masterList.Add(_list); // <<< break here on the second call.
}
}
Run Code Online (Sandbox Code Playgroud)