Why mirrored access to a protected / private class member in C #?

Why is reflection in access a protected / private class member in C #?

Is it not safe for the class, why is reflection given such power? Is it anti-pattern ?

+18
reflection c #
Jan 18 '10 at 6:57
source share
4 answers

This is necessary for scripts such as remote access, serialization, materialization, etc. You should not use it blindly, but note that these tools have always been available in any system (in fact, by directly accessing memory). A reflection simply formalizes it and puts controls and checks in a way that you don’t see, because you are apparently using β€œfull trust”, so you are already stronger than the system that is protected.

If you try this with partial trust, you will see much more control over the internal state.

Is this an anti-pattern?

Only if your code uses it improperly. For example, consider the following (valid for a WCF contract):

[DataMember] private int foo; public int Foo { get {return foo;} set {foo = value;} } 

Is it wrong for WCF to support this? I suspect not ... there are several scenarios in which you want to serialize something that is not part of the public API, without a separate DTO. Similarly, LINQ-to-SQL will be implemented in private members, if you choose.

+19
Jan 18
source share

Item availability is not a security feature. It protects the programmer from himself. This helps to implement encapsulation, but it is by no means a security feature.

The reflection is tedious enough to be used so that people usually do not try to use it to access non-public members. It is also quite slow. Reflection is usually used only in special cases. However, nothing can completely protect against human stupidity, if someone wants to abuse thoughts, he can easily do it, but even without the reflection API they can achieve the same (if they work in full trust, that is), if they are defined enough .

+22
Jan 18
source share

Because it is specified in the ECMA specification , 9 metadata .

+3
Nov 23 2018-10-11T00:
source share

Reflection is absolutely essential for the debugger. Imagine that you are going through your program and cannot see the values ​​of your personal variables. This is probably the reason why reflection works in .NET and Java, how it works to make debugging very easy.

If we do not need debuggers, then I can imagine that reflection will be more limited in the spirit of OOP .

-one
Jan 18 '10 at 7:11
source share



All Articles