The best way I can think of is this.
A set of caller information attributes has been added to C # 5, namely [System.Runtime.CompilerServices.CallerMemberName] , [System.Runtime.CompilerServices.CallerFilePath] and [System.Runtime.CompilerServices.CallerLineNumber] . We can use CallerFilePathAttribute to find out if the caller comes from a specific .cs file.
Typically, a single file contains only one class or structure. For example, ClassA is defined in ClassA.cs . You can check if the caller's ClassA.cs method.
So, change the parameters of your method as follows:
([CallerFilePath] string callerFilePath = "" )
In the method, check if the path to the ClassA file ClassA . If this is not the case, write an exception indicating that access to the method can only be obtained from ClassA !
source share