How to reference current class type using generics

前端 未结 1 523
悲&欢浪女
悲&欢浪女 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<T> where T : TestClass<T>
    {
        public void DoStuffWithFuncRef(Expression<Func<T, object>> expression)
        {
            this.DoStuffWithFuncRef(Property<T>.NameFor(expression));
        }
    }
    

    and derive from it:

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

    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<T> : TestClass where T : TestClass<T>
    

    Of course you should probably make the base classes abstract.

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