Tell me, is it possible to make such a nested type with which you can work from outside (Refer to fields and methods), but that the constructor is not accessible to the external code, but only available to the external class in which it is declared?
- EMNIP, there is no such thing in c #, nor is there any support in the CRL. And why do you need such a thing, maybe somehow you can solve the original problem? A thought comes to my mind only to give proxy methods to the outer class, but there are some crutches ... - AK ♦
- @AK, for example, is an internal type, the existence of which does not make sense outside the external type => I would not like to give the opportunity to freely create a type. - iluxa1810
- And what's the point of giving access to fields and methods outside, if it is a purely internal object? Let the external man himself work with him without showing the details to the world. - AK ♦
- @AK This item is useful for setting private variables (or rather hidden) state, which is sometimes necessary - vitidev
|
1 answer
For such purposes are the interfaces . Expose public fields in any case, ah-ay-ay, but the properties can be completely set in the interface.
We get this design:
class Outer { public IInner CreateInner() { return new Collatz(2017); } public interface IInner { int Curr { get; } void Step(); } class Collatz : IInner { public Collatz(int val) { Curr = val; } public int Curr { get; private set; } public void Step() { Curr = (Curr % 2 == 0) ? (Curr / 2) : (Curr * 3 + 1); } } } That is, the designer is hidden; we can only get an interface from the outside that does not allow us to construct an object.
class Program { static void Main(string[] args) { Outer outer = new Outer(); Outer.IInner inner = outer.CreateInner(); Console.WriteLine(inner.Curr); do { inner.Step(); Console.WriteLine(inner.Curr); } while (inner.Curr > 1); } } |