访问的方法只有当调用类实现特定的接口接口、方法

2023-09-06 10:38:58 作者:森浓不绿

如何限制访问一个成员函数如果调用类没有实现特定的接口在.net(C#) 例如: 类,它实现的 IProfessor ​​只能访问的 IStudent.SetGrade 方式。

How to restrict the access to a member function if the calling class does not implements specific interface in .Net (C#) For example: The class which implements IProfessor only can access IStudent.SetGrade method.

推荐答案

一种选择,你可以考虑,可能实际意义,因为presumably的 IProfessor ​​也可以唯一的集年级的学生,他们教/在他们班/科目等等...

One option you could consider, that might actually make sense since presumably an IProfessor can also only set grades for students they teach / in their classes / subjects etc...

IStudent 不具有 SetGrade 的方法,但一个

IStudent does not HAVE a SetGrade method but a

GetGradeSetterFor(IProfessor教授)

GetGradeSetterFor(IProfessor professor)

,它返回一个对象,允许适当等级的设置。也就是说,它是一个包含了商业逻辑决定谁可以设定什么目标。并给出了通过访问私有方法的学生(比如说)传递一个委托或裁判的私人领域。

which returns an object that allows the setting of the appropriate grades. ie it is that object that contains the 'business logic' deciding who can set what. And is given access to private methods on the student by (say) passing a delegate or ref to a private field.

实事求是,你可能需要一个 GetGradeSetterFor(IGrader年级生)当你允许研修生等,以职系 IProfessor ​​可以实现。

realistically you probably want a GetGradeSetterFor(IGrader grader) for when you allow research students etc to Grade which IProfessor could implement.

aStudent.GetGradeSetterFor(空),但它的通信的到,因为它们可能期望问题签名来电,该呼叫类型的简单运行时检查是不是。

of course you can always call aStudent.GetGradeSetterFor(null) but it's communicating to the caller in the signature that they might expect issues, which a simple runtime check of the calling type is not.

您也可以只具备 IProfessor ​​ SetGrade 的IProfessor一个参数,甚至一个不错的扩展方法等等 aStudent.SetGrade(aProfessor,参数)变成 aProfessor.SetGrade(aStudent,参数)

you could also just have the IProfessor as a param of SetGrade and even a nice extension method in IProfessor so aStudent.SetGrade(aProfessor, args) becomes aProfessor.SetGrade(aStudent, args).

所有这些导致与传递空编译时间问题,但你提醒,一个IProfessor的也许的需要在这种情况下开发。

None of these cause compile time issues with passing in null, but you ARE alerting a developer that an IProfessor might be needed in this situation.