如何使财产的保护,并在C#内部? [英] How to make a property protected AND internal in C#?

查看:92
本文介绍了如何使财产的保护,并在C#内部?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我的缩短抽象类:

Here is my shortened abstract class:

abstract class Report {

    protected internal abstract string[] Headers { get; protected set; }
}

下面是一个派生类:

class OnlineStatusReport : Report {

    static string[] headers = new string[] {
        "Time",
        "Message"
    }

    protected internal override string[] Headers {
        get { return headers; }
        protected set { headers = value; }
    }

    internal OnlineStatusReport() {
        Headers = headers;
    }
}

我们的想法是,我希望能够以能够从在装配的任何地方打电话Report.Headers,但只允许它由派生类来设置。我试图使头只是内部的,但保护不计入不是内部更加严格。有没有一种方法,使头内部和set访问保护和内部?

The idea is, I want to be able to be able to call Report.Headers from anywhere in the assembly, but only allow it to be set by derived classes. I tried making Headers just internal, but protected does not count as more restrictive than internal. Is there a way to make Headers internal and its set accessor protected AND internal?

我觉得我严重滥用的访问修饰符,所以任何设计帮助将不胜AP preciate。

I feel like I'm grossly misusing access modifiers, so any design help would be greatly appreciate.

推荐答案

有什么毛病使得吸气公开?如果财产申报为

What's wrong with making the getter public? If you declare the property as

public string[] Headers { get; protected set; }

符合所有你想要的标准:大会所有成员可以得到财产,只有派生类可以设置它。当然,组件外部类可以获取属性了。所以呢?

it meets all of the criteria you want: all members of the assembly can get the property, and only derived classes can set it. Sure, classes outside the assembly can get the property too. So?

如果你真正需要暴露你的组件内的财产,但不公开,另一种方式来做到这一点是建立一个不同的属性:

If you genuinely need to expose the property within your assembly but not publicly, another way to do it is to create a different property:

protected string[] Headers { get; set; }
internal string[] I_Headers { get { return Headers; } }

当然,它的丑陋与装修名字我_ preFIX。但它是一种怪异的设计。做某种类型的名称重整的内部属性是提醒自己(或其他开发者),他们正在使用的属性是非正统的方式。此外,如果您稍后决定混合无障碍这样是不是真的要你的问题的解决方案,你就会知道解决哪些属性。

Sure, it's ugly decorating the name with that I_ prefix. But it's kind of a weird design. Doing some kind of name mangling on the internal property is a way of reminding yourself (or other developers) that the property they're using is unorthodox. Also, if you later decide that mixing accessibility like this is not really the right solution to your problem, you'll know which properties to fix.

这篇关于如何使财产的保护,并在C#内部?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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