【问题标题】:Accessing generic type parameters used in base class访问基类中使用的泛型类型参数
【发布时间】:2015-09-29 07:53:34
【问题描述】:

由于我不确定我是否能够准确地命名/表述所有内容,所以我将使用一个简单的示例。让我们有以下几点:

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# 语法方法可以访问基类中用于“模板化”的符号类型名称。最初的动机可能是:如果开发人员修改了Derived 类,就像他用Base&lt;OtherType&gt; 替换Base&lt;SomeType&gt; 一样,他还需要在Derived 主体内的所有出现中替换它。对于这些情况,SomeType 与OtherType 兼容,并且还有一个可用的符号名称(如 Base.T),没有其他工作要做。 (是的,我知道,我们有自动重构工具......只是一个问题......)

【问题讨论】:

  • 你通过: Base&lt;SomeType&gt;告诉它T是什么,所以你总是知道它是什么
  • 为什么不直接使用SomeType?鉴于声明,它将始终是 SomeType。
  • "use SomeType 的"通用名称"是什么意思?
  • @Jon Skeet:请注意,我并不是要在运行时确定它,动机是:如果在线上的SomeType class Derived : Base&lt;SomeType&gt; 更改为OtherType,我需要替换所有SomeType 出现在OtherType,这是我不想做的。
  • 那你改变你的Derived类?这肯定是开发过程的一部分吗?感觉就像您在为 Derived 拍摄以某种方式更加“动态”和通用,实际要求是什么?

标签: c# generics inheritance


【解决方案1】:

我认为这可以解决您的问题:

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

}

【讨论】:

  • 有点,但我认为 OP 希望Derived 的成员为T 类型,而不是Base 的成员。
【解决方案2】:
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];
    }
}

【讨论】:

  • 我不是在寻找运行时类型发现。请查看更新后的问题。
  • 不,没有 C# 语法。不过,通过反射,您可以检索所需的信息。
猜你喜欢
  • 2012-01-01
  • 1970-01-01
  • 2021-04-09
  • 2020-07-04
  • 2016-06-23
  • 1970-01-01
  • 1970-01-01
  • 2023-03-18
  • 2012-09-23
相关资源
最近更新 更多