仅当调用类实现特定接口时才访问方法 [英] Access a Method only if calling class implements specific interface

查看:30
本文介绍了仅当调用类实现特定接口时才访问方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果调用类没有实现.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.

推荐答案

您可以考虑的一个选项,这实际上可能是有意义的,因为大概 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 grader),以便在允许研究生等对 IProfessor 可以实现的评分时使用.

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

当然,您始终可以调用 aStudent.GetGradeSetterFor(null),但它会与调用方在签名中沟通他们可能期望出现的问题,这是一个简单的运行时检查调用类型不是.

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, args) 变为 aProfessor.SetGrade(aStudent, args).

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).

这些都不会导致传入 null 的编译时问题,但是您正在提醒开发人员在这种情况下可能需要 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.

这篇关于仅当调用类实现特定接口时才访问方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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