publicstaticclassDevTool { publicstaticbool RestrictCaller<T>(paramsstring[] methods) { StackFrame frame1 = new StackFrame(1); StackFrame frame2 = new StackFrame(2);
var callerMethod = frame2.GetMethod(); var callerType = callerMethod.DeclaringType;
var calleeMethod = frame1.GetMethod(); var calleeType = calleeMethod.DeclaringType;
var calleeId = $"{calleeType.FullName}.{calleeMethod.Name}()";
var expectedType = typeof(T); if (expectedType != callerType) { UnityDebug.LogError($"Call Method:<{calleeId}> withType:<{callerType.FullName}>, expect:<{expectedType.FullName}>"); returnfalse; }
if (methods == null || methods.Length == 0) returntrue; var methodList = new List<string>(methods); if (!methodList.Contains(callerMethod.Name)) { var callerId = $"{callerType.FullName}.{callerMethod.Name}()"; UnityDebug.LogError($"Call Method:<{calleeId}> withMethod:<{callerId}> is not permitted."); returnfalse; } returntrue; }
这样对于上文的例子,我们就可以添加校验
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
publicclassA{ publicstaticvoidCallingValidFromB(){ //限制方法从B调用而来 var callingValid = DevTool.RestrictCaller<B>(); if(!callingValid) return;
// Do something }
publicstaticvoidCallingValidFromBWithDefinedMethod(){ //限制方法只能从 B.TestCall() 中进行调用 var callingValid = DevTool.RestrictCaller<B>(nameof(B.TestCall)); if(!callingValid) return;