I am asking a question about how can I create a static class of outer class which is non-static, and make a static class act as the category of outer class for accessing to specific methods. I do not want users to create an instance of a static class of outer class.
Example:
// OUTER_CLASS.INNER_CLASS.METHODS
var Poinet = new Human(); // OUTER CLASS
Poinet.Eye.Blink(); // Eye is a static class (inner).
Poinet.Mouth.Eat(); // Mouth is a static class.
The reason I am making an inner class static is to prevent users from creating an instance of inner class.
Example of what I don't want to happen:
var Poinet = new Human();
Poinet.Eye eyes = new Poinet.Eye();
eyes.Blink(); // I don't like the way these are implemented.
Is it possible to approach these problems? OR is there any other way of implementing a class that acts as the category of another class for accessing to specific methods?
CodePudding user response:
The reason I am making an inner class static is to prevent users from creating an instance of inner class.
That's not what static
is for, that's just a side effect of it. What you actually seem to want, for some reason, is singletons. Something like this:
class O
{
public class IT
{
internal IT() { }
public void F() { }
}
public IT I { get; } = new();
}
// called as:
var o = new O();
o.I.F();
CodePudding user response:
No, you can't reference a static member or inner type from an instance variable. There are ways to keep users from creating the inner type, or from modifying the member, but not from referencing it. In other words, if a user can do this:
Poinet.Eye.Blink();
Then they can do this
var eye = Poinet.Eye;
eye.Blink();
But you can make it so that users either can't create an Eye
, or change the value of Eye
, or both.
Also note that static
is probably not what you want anyway, since static
members are "shared" by all instances, so in this example the Eye
definitely belongs to the Person
instance.
I suspect you want something like this:
public class Human
{
public _Eye Eye {get;} = new _Eye();
public _Mouth Mouth {get;} = new _Mouth();
public class _Eye {
internal _Eye() { return; } // don't let users create this type
public void Blink() { return; }
}
public class _Mouth {
internal _Mouth() { return; } // don't let users create this type
public void Eat() { return; }
}
}