c# - 非常奇怪的 C# 泛型问题

标签 c# generics list

这段代码可以编译,但看起来很奇怪。 我这里有一个典型而简单的父/子关系,它是以一种非常奇怪的方式使用泛型实现的。 但我似乎找不到任何其他方法。

class SampleObject<T> //I don't want to make this a generic but am forced to
{
  //The SampleContainer this object is in
  //This must be located in this base class
  public SampleContainer<T> Parent { get; set; }
}

class SpecificObject : SampleObject<SpecificObject>
//SampleObject<SpecificObject> !!? This is the bizzare bit
//It seems really strange but necessary for compilation to work
{
}


//A class to contain a List of objects derived from SampleObjects
class SampleContainer<T>
{
  public List<T> List;
}


class Start
{
  public void Test()
  {
    SampleContainer<SpecificObject> container = new SampleContainer<SpecificObject>();

    SpecificObject o = new SpecificObject(); //create an object
    container.List.Add(o); //add it to the list
    o.Parent = container; //set its parent
  }
}

这段代码可以简化吗?

最佳答案

这似乎没有类型。

这就是您要找的吗?

class SampleObject //I don't want to make this a generic but am forced to
    {

        //The SampleContainer this object is in
        //This must be located in this base class
        public SampleContainer<SampleObject> Parent;//{ get; set; }
    }

    class SpecificObject : SampleObject
    //SampleObject<SpecificObject> !!? This is the bizzare bit
    //It seems really strange but necessary for compilation to work
    {
    }


    //A class to contain a List of objects derived from SampleObjects
    class SampleContainer<T>
    {
        public List<T> List;
    }


    class Start
    {
        public void Test()
        {
            SampleContainer<SampleObject> container = new SampleContainer<SampleObject>();

            SpecificObject o = new SpecificObject(); //create an object
            container.List.Add(o); //add it to the list
            o.Parent = container; //set its parent
        }
    }

关于c# - 非常奇怪的 C# 泛型问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1496126/

相关文章:

c# - 对删除重复引用一无所知

c# - 从内部函数的代码中退出所有函数

c# - 如何定位组件间引用的 DLL

list - Prolog 逆向列表前面的成员

list - 如何使用 sml 编写函数将 2 元组列表转换为扁平列表?

java - Java 中的 map 和列表

c# - SQLiteConnection 是否在事务内部处理?

java - 在抽象方法中使用子类作为参数和返回类型

java - 从 InputStream 读取非泛型 HashMap 时发出警告

java: HashMap<String, int> 不工作