开发者

Protection of acces with Auto-Implemented Properties in C#

A simple example. alt text http://img19.imageshack.us/img19/1854/51445300.jpg

A have a class TDMReader which is a buldier of TDMFile objects and I am using Auto Implemented Properties f.e.

    public string Name
    {
        get;
        set;
    }

    public Group[] Groups
    {
        get;
        set;
    }  

What I want to do is to make setter accessible only for TDMReader methods. In C++ i could have friends methods to access private variables, in Java I could make them in one packet and so 开发者_C百科access to fields. I have some ideas but with this auto-implemetation is a bit more complicated to do. Any ideas with a nite solution?:)


Automatic properties have no bearing on this - the same options are available for automatic properties and "manual" properties. You can restrict the access of the setter like this:

// Setter access only to this type and nested types
public string Name { get; private set; }
// Setter access within the assembly
public Group[] Groups { get; internal set; }

etc

... but you can't do it for a single class (unless that class is nested within the declaring type, in which case private would be fine). There's no namespace-restricted access in .NET or C#.

(It's not entirely clear which class the properties are declared in - if they're TdmReader properties, then just make them private. If they're TdmFile properties, you have the problem described above.)


Like this:

public string Name
{
    get;
    private set;
}

public Group[] Groups
{
    get;
    private set;
}  

By adding the private keyword, the setters will only be accessible by code in the same class. You can also add internal to make it accessible to code in the same project.


Note that exposing an array as a property is extremely poor design.
Instead, you should expose a Collection<Group> or ReadOnlyCollection<Group>, in the System.Collections.ObjectModel namespace.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜