访问孩子的静态属性在父类的方法 [英] Accessing a static property of a child in a parent method

查看:119
本文介绍了访问孩子的静态属性在父类的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有下面的代码:

class Parent
{

    static string MyField = "ParentField";

    public virtual string DoSomething()
    {
        return MyField;
    }
}

class Child : Parent
{
    static new string MyField = "ChildField";
}

现在我希望能够做以下两项操作:

Now I want to be able to do both of the following:

Console.WriteLine(Parent.MyField);
Console.WriteLine(Child.MyField);



如预期的这些工作,但我也想做到这一点:

These work as expected, but I would also like to do this:

Child c = new Child();
Console.WriteLine(c.DoSomething());



由于DoSomething的()没有针对儿童类中定义的,它是被返回的家长MyField的,但。我要的是孩子的MyField的

Since DoSomething() is not defined for the Child class, it's the Parent's MyField that gets returned, but what I want is the Child's MyField.

所以我的问题是:有没有什么办法可以做到这一点。

So my question is: Is there any way I can do this?

请注意:重写方法在子类中是一种选择,但因为我将有很多子类从父继承和方法应该做同样的在所有的人,在这种方法来改变的东西会带来不少麻烦。

NOTE: Overriding the method in the Child class is an option, but since I will have lots of Child classes inheriting from the Parent and the method is supposed to do the same in all of them, changing something in this method would bring a lot of trouble.

推荐答案

如果你发现自己需要不受语言支持的结构,在这种情况下静态虚拟成员,这是一个气味,说明你可能有一个设计缺陷。

If you find yourself requiring a construct not supported by the language, in this case static virtual members, that is a smell, indicating you might have a faulty design.

而不是向我们展示一个解决方案,向我们展示问题你正试图与解决方案来解决。我的猜测是,有一个完全不同的设计,消除了这一奇怪现象,需要

Instead of showing us a solution, show us the problem you are trying to solve with that solution. My guess is that there is a totally different design that eliminates the need for this oddity.

换句话说:你接受的答案是不是你想要的因为你问的问题是不是真的,你应该问的问题。我能想到的任何情况下所提出的设计提供了好处,另一种更常规的设计没有。

Put another way: the answers you've received aren't the ones you want because the question you asked is not really the question you should be asking. I can think of no situation where the proposed design offers benefits that another, more conventional design does not.

这篇关于访问孩子的静态属性在父类的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆