简体   繁体   English

如何使用泛型引用当前类类型

[英]How to reference current class type using generics

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. 现在,我想强制T为实例化类的类型,我希望这将导致C#编译器自动理解要使用的泛型类型。 Eg I would like to avoid coding the doStuff method below, where I have to specify the correct type - but rather use the doStuffILikeButCannotGetToWork method: 例如,我想避免编写下面的doStuff方法,我必须指定正确的类型 - 而是使用doStuffILikeButCannotGetToWork方法:

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? 我应该以不同的方式做这件事吗?

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. 当然你应该把基类抽象化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM