在基类静态方法中获取派生类属性 - 谜题! :)

发布于 2024-11-08 00:17:58 字数 512 浏览 9 评论 0原文

我想详细说明我正在从事的当前项目,但这会很长。相反,我只会发布一个编程谜题,它基本上解释了我想要完成的任务。 :)

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

能怎样 2024-11-15 00:17:58

在基类中没有简单(有效)的方法来做到这一点。
只需在每个派生类中实现一个静态构造函数并使用它来注册属性即可。

另请查看 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.

So尛奶瓶 2024-11-15 00:17:58

如果您可以等待子类型的实例被实例化,那么您可以使用 A 的常规构造函数来注册实现类:

public A()
{
    Type childType = GetType();
    string className = childType.Name;
    if (!_DerivedPropertyNames.ContainsKey(className)) {
         // add properties for this class
    }
}

在任何实例化之前,您将很难在静态构造函数中完成工作,而不添加子类中的逻辑(我想你不想要)。原因是当调用 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:

public A()
{
    Type childType = GetType();
    string className = childType.Name;
    if (!_DerivedPropertyNames.ContainsKey(className)) {
         // add properties for this 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文