Pregunta

Is there a way to modify the access of some attribute to a specific class? More specifically, I want to create a property that has a public get, but can only be set by a certain class.

Example:

public Class1
{
    Class2.SomeInt = 5;
}

public static Class2
{
    private static int someInt;
    public static int SomeInt
    {
        get { return someInt; }
        (give access to Class1 only somehow?) set { someInt = value; }
    }
}

Update (more info): I'm doing this in xna, I want the main type (Game1) to be the only thing that can modify a static helper class. It's for a group project in school, we're using SVN (not sure how that'd be relevant), I could just tell everyone in my group to avoid setting the values, but I was wondering if there was a better way.

¿Fue útil?

Solución

This sounds like the friend access modifier, which C# doesn't have. The closest I've seen to this in C# is to have the "unrelated" class be an interface and have a private implementation within a class. Something like this:

public interface IWidget
{
    void DoSomethingPublic();
}

public class SomeObject
{
    private ObjectWidget _myWidget = new ObjectWidget();
    public IWidget MyWidget
    {
        get { return _myWidget; }
    }

    private class ObjectWidget
    {
        public void DoSomethingPublic()
        {
            // implement the interface
        }

        public void DoSomethingPrivate()
        {
            // this method can only be called from within SomeObject
        }
    }
}

Code external to SomeObject can interact with MyWidget and sees anything that's on the IWidget interface, but code internal to SomeObject can also non-interface public members on MyWidget.

Otros consejos

It seems to be impossible in C#. You can only use public, protected, protected internal, internal and private access modifiers.
But you can, for instance, make an assembly that contains only these two classes and set the internal modifier for the SomeInt setter or nest one class into another.
If you want to just hide a setter from the IntelliSense, you can define this setter in some interface and implement it explicitly:

public interface IHidden<T>
{
    T HiddenPropery { set; }
}

public class SomeClass : IHidden<int>
{
    private int someInt;
    public int HiddenPropery
    {
        get { return someInt; }
    }

    int IHidden<int>.HiddenPropery
    {
        set { someInt = value; }
    }
}

Usage:

// This works:
((IHidden<int>)new SomeClass()).HiddenPropery = 1;
// This doesn't:
new SomeClass().HiddenPropery = 1;
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top