如何使用泛型引用当前类的类型 [英] How to reference current class type using generics

查看:86
本文介绍了如何使用泛型引用当前类的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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));
        }
}

现在,我想强制T为实例化类的类型,我希望这将导致C#编译器自动理解要使用的泛型类型.例如.我想避免在下面的doStuff方法中编写代码,在该方法中必须指定正确的类型-而是使用doStuffILikeButCannotGetToWork方法:

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?

推荐答案

使基类本身具有通用性:

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));
    }
}

并从中得出:

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.

这篇关于如何使用泛型引用当前类的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆