【问题标题】:How to get the type of derived class at base class without generics?如何在没有泛型的情况下在基类中获取派生类的类型?
【发布时间】:2011-07-06 11:52:03
【问题描述】:

我的基类使用派生类的反射来为它们提供一些功能。目前我是这样做的:

abstract class BaseClass<T>
{
    string GetClassString()
    {
        // Iterate through derived class, and play with it's properties
        // So I need to know the type of derived class (here T).
        return result;
    }

    static bool TryParse(string classString, out T result)
    {
        // I should declare a variable as T and return it
    }
}

我可以在没有泛型的情况下这样做吗?

【问题讨论】:

  • T 不是派生类的类型——或者至少不是必须的。想象一下class MyDerivedClass : BaseClass&lt;string&gt;。这里派生类是MyDerivedClass,但Tstring
  • @Jon: 那么如何声明TryParse(string classString, out T derivedType) 呢? C# 是否让我在方法签名中动态定义 derivedType 而不要使用 T

标签: c# generics types base-class


【解决方案1】:

编辑:

抱歉,您需要类型参数(即typeof(T))。 在这种情况下,您仍然使用this.GetType(),但您在之后添加.GetGenericArguments()[0]

尝试解析: 你需要创建一个你不知道的类型的新实例

有两种方法: 首先,在不改变其余部分的情况下,使用 Activator 类和以下代码:

result = (T) Activator.CreateInstance(typeof(T))

(MSDN).

然后,您可以为您的类型添加一个“新”约束:

MyClass<T> where T : new() {...}
result = new T();

这两个示例都需要无参数构造函数。如果要传递参数,则需要深入 System.Reflection 内部,获取构造函数列表并调用所需的构造函数。工厂模式也可以完成这项工作。

【讨论】:

    猜你喜欢
    • 2012-09-08
    • 2014-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多