Generic class from type parameter

前端 未结 2 531
情书的邮戳
情书的邮戳 2021-01-12 22:32

Is there a way to create a generic class from type parameter.

I have something like this:

public class SomeClass
{
    public Type TypeOfAnotherClass         


        
2条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-12 23:26

    I'm not sure what exactly you are asking here. If I understood you properly, this is what you are looking for:

    public class GenericClass
    {
        public static GenericClass GetInstance(T ignored)
            where T : class
        {
            return new GenericClass();
        }
    
        public static GenericClass GetInstance()
            where T : class
        {
            return new GenericClass();
        }
    }
    

    Th usage:

      var generic1 = GenericClass.GetInstance();
      var generic2 = GenericClass.GetInstance(new OneMoreClass());
    

    Assertions:

    Assert.AreEqual(typeof(GenericClass), generic1.GetType());
    Assert.AreEqual(typeof(GenericClass), generic2.GetType());
    

提交回复
热议问题