How to reference current class type using generics

前端 未结 1 539
悲&欢浪女
悲&欢浪女 2021-02-05 09:10

I have a base class, with a method, where I would like to use generics to force the coder to use a generic expression on the current class:

public class TestClas         


        
1条回答
  •  無奈伤痛
    2021-02-05 09:52

    Make the base class itself generic:

    public class TestClass where T : TestClass
    {
        public void DoStuffWithFuncRef(Expression> expression)
        {
            this.DoStuffWithFuncRef(Property.NameFor(expression));
        }
    }
    

    and derive from it:

    public class SubTestClass : TestClass {
         // ...
    }
    

    If you need to have an inheritance hierarchy with a single root, inherit the generic base class from another non-generic version:

    public class TestClass { ... }
    public class TestClass : TestClass where T : TestClass
    

    Of course you should probably make the base classes abstract.

    0 讨论(0)
提交回复
热议问题