How to reference current class type using generics

2020-05-25 07:37发布

问题:

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 TestClass
{
    public void DoStuffWithFuncRef<T>(Expression<Func<T, object>> expression) where T : TestClass
        {
            this.DoStuffWithFuncRef(Property<T>.NameFor(expression));
        }
}

Now, I would like to force T to be of the type of the instantiated class, which I hope will the cause the C# compiler to automatically understand the generic type to use. E.g. I would like to avoid coding the doStuff method below, where I have to specify the correct type - but rather use the doStuffILikeButCannotGetToWork method:

public class SubTestClass : TestClass
{
    public string AProperty { get; set; }

    public void doStuff()
    {
        this.DoStuffWithFuncRef<SubTestClass>(e => e.AProperty);
    }

    public void doStuffILikeButCannotGetToWork()
    {
        this.DoStuffWithFuncRef(e => e.AProperty);
    }
}

Is this possible? Should I be doing this in a different way?

回答1:

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.



标签: c# generics