简体   繁体   中英

Restrict method visibility when passing instance to user procedure in C#

I am trying to define a class where "I" have access to all public methods but when I pass an instance off to a user-supplied function, they can only access a subset of the public methods. Something along these lines:

// usercl.cs
class UserClass {
    public void UserM1();
    public int UserM2(int x);
}

// mastercl.cs
class MasterClass : UserClass {
    public void MasterM3(float y);
    public float MasterM4(int z);
}

// UserCode.cs
...
public void UserFunction(UserClass uc);
...

// Master.cs
MasterClass  mc = new MasterClass();
UserFunction( (UserClass)mc );

But, of course, as implemented above, the user can simply recast it to (MasterClass) and then have access to the Master methods. I tried putting the UserClass in a separate (user) namespace but this ran into a "Cannnot convert type X to Y" compile error in the call to the UserFunction.

I also tried various things with multiple Interface instances (IMaster / IUser), none of which seemed to work, and a couple stabs at using abstract classes (which hurt my head and produced no better results).

What DID seem to work was to define the MasterClass within my code. I could then recast it to "(UserClass)" when calling the UserFunction and the user would not have visibility to the Master methods. However, give that I may need to have a (large?) number of such classes, this is really going to clutter up my primary program/file. I'd be interested in knowing if there is a better/nicer/easier/(?) way to do what I want?

Instead of using inheritance create a wrapper class that implements the "really public" functions. That wrapper simply passes off the parameters to the held instance reference. Because the wrapper doesn't derive from the internal type you don't run into an ability to cast.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM