泛型参数 class 和泛型参数 Subclass

Generic type argumented class with generic type argumented Subclass

我有一个 class 具有通用类型,如下所示:

public class Test<T> {
    /*
       Some Properties and Fields
    */
}

现在我需要 public 属性 SubTest{T} in class Test{T} 数据类型为 Test{T}

public class Test<T> {
    /*
       Some Properties and Fields
    */
    public Test<T> SubTest { get; set; }
}

T 和 U 不是相同的数据类型,SubTest 可以为空。 这在 C# 中可能吗?

更新 或者像这样?

public class Test {
    /*
       Some Properties and Fields
    */
    public Type ElementType { get; private set; }
    public Test SubTest { get; set; }

    public Test(Type elementType) {
        ElementType = elementType;
    }
}

你没有定义所以不能像.您需要在 class 中创建类型参数,或者使用特定类型,例如 string:

public class Test<T, U> {
      /*
         Some Properties and Fields
      */

      public Test<T,U> SubTest { get; set; }
    }

你的问题有点前后矛盾:

Now I need a public Property SubTest{T} in class Test{T} with datatype Test{T}

但是你的例子不一样,现在加了U

public class Test<T> 
{
    public Test<U> SubTest { get; set; }
}

因此,要按原样回答您的问题,请将 U 替换为 T:

public class Test<T> 
{
    public Test<T> SubTest { get; set; }
}

我想你要做的是创建一个通用的 "test" 对象,然后有多个实现(不同类型)。我会改用接口,但它与 类.

的概念相同
public interface ITest
{
    // general test stuff
}

// Type-specific stuff
public interface ITesty<T> : ITest
{
     public ITest SubTest { get; set; }    // a sub-test of any type
}