【发布时间】:2015-01-07 04:50:59
【问题描述】:
我想强制我的子类将自己作为泛型参数传递给父类。
例如:
class BaseClass<T> where T: BaseClass
{
//FullClassName : Tuple [Save,Update,Delete]
Dictionary<string,Tuple<delegate,delegate,delegate>> dict = new Dictionary...;
static BaseClass()
{
RegisterType();
}
private static void RegisterType()
{
Type t = typeof(T);
var props = t.GetProperties().Where(/* Read all properties with the SomeCustomAttribute */);
/* Create the delegates using expression trees and add the final tuple to the dictionary */
}
public virtual void Save()
{
delegate d = dict[t.GetType().FullName];
d.Item1(this);
}
}
class ChildClass : BaseClass<ChildClass>
{
[SomeCustomAttribute]
public int SomeID {get;set;}
[SomeCustomAttribute]
public string SomeName {get; set;}
}
public class Program
{
public static void Main(string[] args)
{
ChildClass c = new ChildClass();
c.Save();
}
}
显然上面的代码不会编译。我会重申:我希望子类将自身作为通用参数传递,而不是 BaseClass 的任何其他子类。
(上面的代码是一种伪代码,仍然无法编译)。
【问题讨论】:
-
afaik:你不能强求。但你不必。您可以简单地调用
GetType来获取实例的运行时类型。 -
如果有人能够了解我想要完成的工作,他们能否提供替代方案。主要问题是为每个子类自动执行一次性静态方法。我认为静态构造函数只会对基类执行一次,而不是对每个子类执行一次。
-
现在看到...考虑一下,如果简单地反映所有类型并注册派生类是否可行。
-
我认为一个潜在的问题可能是类型存在于多个程序集中,我不确定如何以及何时加载每个程序集。我的代码应该只执行一次,这样就没有不必要的处理。
-
很明显这是一个 XY 问题。