从dervied类C#隐藏基类的一些性质 [英] c# hide from dervied classes some properties of base class

查看:209
本文介绍了从dervied类C#隐藏基类的一些性质的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道,如果它可以隐藏从派生类的基类属性:

I want to know if its possible to hide a base class property from a derived class:

例如:

    class BaseDocument
    {
        public string DocPath{get; set;}
        public string DocContent{get; set;}
    } 

    class DerviedDocument: BaseDocument
    {
     //this class should not get the DocContent property
        public Test()
        {
           DerivedDocument d = new DerivedDocument();
           d.//intellisense should only show me DocPath
             //I do not want this class to see the DocContent property
        }
    }

我不能做的DOCPROPERTY私人,因为我要到别处实例化BaseDocument类,并使用属性那里。那会杀了一个属性的主意。

I cannot make the the Docproperty private, because i want to instantiate the BaseDocument class elsewhere and use the property there. Thats will kill the idea of a property anyway.

要解决这个问题是使用一个接口的一种方法,说的IDoc,这暴露DocPath财产,使双方的BaseDocument和DerivedDocument实现的接口。这虽然会打破他们的亲子关系。

One way to fix this would be to use a interface, say IDoc, which exposes DocPath property and make both the BaseDocument and DerivedDocument implement the interface. This will break their parent-child relationship though.

我可以用新的游戏和override关键字,但那不是正确的方式要么是因为孩子还是'看到'的属性。

I can play with the new and override keywords, but thats not the right way either because the child still 'sees' the property

我试图用对DocContent的密封的关键字,但是这似乎并没有解决此问题有两个。

I tried using the 'sealed' keyword on the DocContent, but that does not seem to solve the problem either.

据我所知,休息的继承,但我想这种情况应该经常来了,其中一个孩子需要得到一切从父,但两个属性之一,母公司已被宣布为一个基类。

I understand that it 'breaks' inheritance, but I guess this scenario should be coming up frequently where a child needs to get everything else from the parent but one of two properties and the parent has been declared as a base class.

试问,这样的场景被正常处理?

How can such scenarios be handled gracefully?

推荐答案

我不知道继承将是一段路要走这里。是的,你可以通过使用 EditorBrowsableAttribute 周围破解但我认为设计应该重新考虑。一种可能的方法:

I'm not sure inheritance would be the way to go here. Yes, you can hack around it by using the EditorBrowsableAttribute but I think the design should be rethought. One possible approach:

public interface IDoc
{
   DocPath{get;set;}
}

class BaseDocument : IDoc
{
     public DocPath{get; set;}
     public DocContent{get; set;}
} 

class DerviedDocument
{
    public DerivedDocument(IDoc doc)
    {
        this.Doc = doc;
    }

    public IDoc Doc{get;set;}

     public Test()
     {
        DerivedDocument d = new DerivedDocument(new BaseDocument());
        d.//here you will only see d.IDoc which only exposes DocPath

     }
}

基本上,使用组成,而不是继承和程序界面,而不是一个实现。

Basically, use composition instead of inheritance, and program to an interface, not to an implementation.

这篇关于从dervied类C#隐藏基类的一些性质的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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