首页 文章

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

提问于
浏览
16

我有一个基类,有一个方法,我想使用泛型来强制编码器在当前类上使用泛型表达式:

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

现在,我想强制T为实例化类的类型,我希望这将导致C#编译器自动理解要使用的泛型类型 . 例如 . 我想避免编写下面的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);
    }
}

这可能吗?我应该以不同的方式做这件事吗?

1 回答

  • 19

    使基类本身通用:

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

    并从中得出:

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

    如果需要具有单个根的继承层次结构,则从另一个非泛型版本继承通用基类:

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

    当然你应该把基类抽象化 .

相关问题