访问基类中使用的泛型类型参数

本文关键字:泛型类型参数 基类 访问 | 更新日期: 2023-09-27 18:14:54

由于我不确定我是否能够精确地命名/表述所有内容,因此我将使用一个简单的示例。

class Base<T>
{
    ...
}
/*
 * Please note the Derived is not generic, only derives from generic class
 */
class Derived : Base<SomeType>
{
    /*
     * Here, I would like to use SomeType's "generic name" (like the T in the Base), 
     * so it might look like:
     */
    Base.T field1; // This would translate to 'SomeType field1' for this particular case
    ...
}

C#语法中是否有访问Base.T的方法?

当然我知道这样一个事实,如果我们使Derived也是泛型的,我们可以将其类型参数传递给Base并在Derived中使用它。

编辑:


请考虑这是一个理论问题,我想确定,如果有一个C#语法的方式来达到基类中用于"模板化"的符号类型名称。最初的动机可能是:如果开发人员以用Base<OtherType>替换Base<SomeType>的方式修改Derived类,那么他也需要在Derived主体中的所有出现中替换它。对于这种情况,SomeTypeOtherType兼容,并且还有一个可用的符号名称(如Base.T),不需要做其他工作。(是的,我知道,我们有自动重构工具……只是一个问题…)

访问基类中使用的泛型类型参数

我认为这解决了你的问题:

class Base<T> 
{
    protected T field1;
}
/*
 * Please note the Derived is not generic, only derives from generic class
 */
class Derived : Base<string> 
{
    /*
     * Here, I would like to use SomeType's "generic name" (like the T in the Base), 
     * so it might look like:
     */
    //[not necessary]
    //Base.T field1; // This would translate to 'SomeType field1' for this particular case
    public Derived()
    {
        field1 = "hello world";
    }
}
class Base<T>
{
    protected T SomeField;
}
class Derived : Base<SomeType>
{
    private Type GetSomeType(bool asConstructed)
    {
        // here SomeField is SomeType because Derived is a constructed type.
        if (asConstructed)
           return SomeField.GetType(); // of course, if SomeField is null, use GetField instead
        // However, you can get the T if you really want:
        return this.GetType().BaseType.GetGenericTypeDefinition().GetGenericArguments()[0];
    }
}