Is there a way to restrict access to a public method to only a specific class in C#?

后端 未结 5 1478
萌比男神i
萌比男神i 2021-01-12 06:30

I have a class A with a public method in C#. I want to allow access to this method to only class B. Is this possible?

UPDATE:

This is what i

5条回答
  •  情书的邮戳
    2021-01-12 07:06

    There is no out-of-the-box answer for your question.

    If they are already in the same assembly, why not make the method internal scoped instead?

    If they are in different assemblies, you can use the "friend" syntax which covers all internal methods.

    Probably your best solution is to limit access to the public methods to specific assembly(ies). Which means that someone cannot just write a new assembly and go ahead an call your public methods. Given that you seem to have a domain model, it looks like you should allow this method to be called from other domain objects, but perhaps not from the business logic. This can be achieved by assigning a unique strong name to domain model DLL's.

    You can restrict access to a public method to only allow it to be called by methods in assemblies satisfying a given public key. see msdn StrongNameIdentityPermission

提交回复
热议问题