How can I protect my private funcs against reflection executing?

前端 未结 9 1208
深忆病人
深忆病人 2020-12-05 15:05

After seeing this: Do access modifiers affect reflection also?

I tried using this, but it doesn\'t work: \"enter

9条回答
  •  情歌与酒
    2020-12-05 16:03

    Though I absolutely agree with the idea of access modifiers not being a security feature, just for the sake of programming I've been thinking a bit about this, and I've got a simple, not much useful mechanism, fight Reflection with Reflection :-)

    Be advised, it's just a silly proof of concept, I'm not taking into account Generic methods, it would need changes for that...

    The idea is, at the start of every private method that you want to secure from being "illegally" invoked, you just check via Reflection that you're being invoked from another method in that class, not from outside. So you would use: new StackTrace().GetFrame(1).GetMethod(); to get the MethodBase of your invoker and would compare it against the list of MethodInfos for your class.

    You can add it to a helper class (anyway you'll need a IEqualityComparer to compare MethodBases...

    One problem is that you would also be preventing some correct invocations, like invoking it through a delegate or through Reflection from another of your methods... so you should be careful with when you use it.

    You can my implementation here

提交回复
热议问题