限制Class对象访问仅限特定方法 [英] Restrict Class object to access Only particular methods

查看:68
本文介绍了限制Class对象访问仅限特定方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,有CLASS A课程,其中包含15个方法。并将对象创建为CLASS A,如A1,A2,A3。



实例A1仅访问前五个方法A的方法不是剩余的方法。



实例A2只能访问第二种方法类别A的方法不是剩余的方法。



仅限实例A3访问前五方法A的方法不是剩下的方法。



如何以这种方式限制对象。







谢谢

Hi There is class CLASS A which contains 15 Methods. And creating the object to CLASS A like A1,A2,A3 .

Instance A1 only access first five Methods of that CLASS A Not the remaining Methods.

Instance A2 only access second five Methods of that CLASS A Not the remaining Methods.

Instance A3 only access Last five Methods of that CLASS A Not the remaining Methods.

How to restrict object in this manner.



Thanks

推荐答案

你不能在类中这样做,但是你可以创建接口来显示/隐藏你想要的方法(这可以规避)。



You cannot do this in classes, however you can create interfaces to show/hide methods you want (this can be circumvented).

public interface Ifirst
{
   void Method1();
}

public interface Isecond
{
   void Method2(); 
}

public class A : Ifirst, Isecond
{ 
...
}

public void DoSomething(Ifirst o)
{
   o.Method1(); // only accessible
}

public void Main()
{
   A a = new A();

   DoSomething(a);
}


您不能逐个实例限制对实例的访问 - 您可以做的最好的事情是创建一个抽象基类包含常见的预测,方法等,并为您想要提供的每组方法实现派生版本。



You can''t restrict access on an instance by instance basis - the best you can do is to create an abstract base class which contains the common propteries, methods and so forth, and implement derived versions of that for each set of methods you want to have available.

public abstract class A {}
public class A1 : A
   {
   public void DoSomething(){}
   }
public class A2 : A
   {
   public void DoSomethingElse(){}
   }

...


A either = new A1();
A1 A1Only = new A1();
A2 A2Only = new A2();
either = A2Only;
A1Only.DoSomething();
A2Only.DoSomethingElse();

所有这些都是合法的。

All of those are legal.

A1Only = A2Only;
A1Only.DoSomethingElse();
A2Only.DoSomething()

所有这些都会导致编译错误。

All of those will cause compilation errors.


执行此操作的最佳方法是为每组设置接口功能。让您的类实现所有三个接口。你创建实例的地方在接口变量上有类的实例。



ie



接口和方法



I1 - > A1,A2,A3

I2 - > B1,B2,B3



班级

A类:I1,I2



使用



I1 a1 = new A();这将仅访问A1,A2,A3

I2 s2 = new A();这将仅访问B1,B2,B3



更新:Mehdi Gholam为此提供了代码。它似乎是完美的解决方案。
The best way to do this is to have the interfaces for each set of functions. Have your class implement all three interfaces. the place where you are creating the instances have the instances of the class on the interface variable.

i.e.

interface and methods

I1 -> A1, A2, A3
I2 -> B1, B2, B3

the class
class A : I1, I2

the use

I1 a1 = new A(); this will access only A1,A2,A3
I2 s2 = new A(); this will access only B1,B2,B3

UPDATE: Mehdi Gholam has given a code for this. it seems to be the perfect solution.


这篇关于限制Class对象访问仅限特定方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆