在基类静态方法中获取派生类属性 - 谜题! :)
我想详细说明我正在从事的当前项目,但这会很长。相反,我只会发布一个编程谜题,它基本上解释了我想要完成的任务。 :)
abstract class A
{
// key = Derived Class name, value = list of properties the derive class exposes.
private static Dictionary<string, List<string>> _DerivedPropertyNames;
static A()
{
InitializeDerivedPropertyNames();
}
private static void InitializeDerivedPropertyNames()
{
//...???...
}
}
谜语是如何创建一个抽象基类来保存其所有派生类属性的静态缓存?
请注意,这个想法是避免按名称加载程序集。
I wanted to elaborate on the current project i'm working on but that would be kind long. Instead I'll just post a programming riddle which basically explains what i'm trying to accomplish. :)
abstract class A
{
// key = Derived Class name, value = list of properties the derive class exposes.
private static Dictionary<string, List<string>> _DerivedPropertyNames;
static A()
{
InitializeDerivedPropertyNames();
}
private static void InitializeDerivedPropertyNames()
{
//...???...
}
}
The riddle is how can you create an abstract base class which will hold a static cache of all its derived classes properties?
Note that the idea is to avoid loading an assembly by name.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在基类中没有简单(有效)的方法来做到这一点。
只需在每个派生类中实现一个静态构造函数并使用它来注册属性即可。
另请查看 WPF Fx 中的依赖关系属性,以进行比较。
There is no easy (efficient) way to do this in the base class.
Simply implement a static constructor in every derived class and use it to register the properties.
Also take a look at Dependency properties in the WPF Fx, for comparison.
如果您可以等待子类型的实例被实例化,那么您可以使用 A 的常规构造函数来注册实现类:
在任何实例化之前,您将很难在静态构造函数中完成工作,而不添加子类中的逻辑(我想你不想要)。原因是当调用 A 的静态构造函数时,您将无法强制加载所有包含实现 A 的类型的程序集。
If you can wait for instances of the child types to be instantiated, then you could use A's regular constructor to register the implementing class:
It will be very difficult for you to get the job done in the static constructor, before any instantiation, without adding logic in the child classes (which I suppose you don't want). The reason is that you won't be able to enforce all assemblies containing types that implement A to be loaded when A's static constructor is called.