[英]Using Generics in Base Classes in C#: How to ensure methods in the base class return the derived class's type?
[英]How to get the type of derived class at base class without generics?
我的基类在派生类上使用反射来为其提供一些功能。 目前,我是这样进行的:
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
}
}
没有泛型,我可以这样做吗?
编辑:
抱歉,您需要类型参数(即typeof(T)
)。 在那种情况下,您仍然使用this.GetType()
但在.GetGenericArguments()[0]
添加.GetGenericArguments()[0]
。
尝试解析:您需要创建一个未知类型的新实例
有两种方法:首先,不更改其余部分,使用Activator类和以下代码:
result = (T) Activator.CreateInstance(typeof(T))
( MSDN )。
然后,您可以在类型中添加“新”约束:
MyClass<T> where T : new() {...}
result = new T();
这两个示例都需要较少参数的构造函数。 如果要传递参数,则需要更深入地研究System.Reflection,获取构造函数列表并调用所需的构造函数。 工厂模式也可以完成这项工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.