C # - How to prevent class member access?

I have a class (myClass) that contains a private member of the class (currentData of type myData). I have a property (CurrentData) that allows me to "get" this member. I want to allow users to call functions in currentData, but does not allow them to use an external link to it. For instance.

myClass a = new myClass();

// This is OK
a.CurrentData.somefunc();

// This is what I dont want
myData m = new myData();
m = a.CurrentData;
// ... some time passes here...
m.someFunc();

Although I understand that they refer to the same object. I do not want the link to be stored outside my class in the inner member, since the inner member could change unexpectedly.

Is it possible? I have been away from C # for so long that I can’t remember how it all works!

+4
source share
4 answers

No way to do

a.CurrentData.somefunc();

legal but

m = a.CurrentData;

. a.CurrentData.somefunc(); a.CurrentData, somefunc() .

, , :

public void DoSomeFuncWithCurrentData()
{
   this.currentData.someFunc();
}

myClass a = new myClass();

a.DoSomeFuncWithCurrentData();
+9

"" .

:

  • -. CurrentData . - , CurrentData:

    myClass a = new myClass();
    a.SomeFuncOnCurrentData();
    

    , . , ( , ).

  • . CurrentData GetCurrentData . , "" , , .

  • . MyData . CurrentData , MyData, MyData. , ( ), , .

  • . CurrentData :

    • MyData,
    • , - someFunc ObjectExpiredException.
+3

, , :

  • - , . , .NET .
  • - , , .

- , . , .

+1

:

a.CurrentData.somefunc();

:

var currentData = a.CurrentData;
currentData.someFunc();

(.. ) . , , , myClass. , someFunc() myClass, () , myClass .

, , CurrentData, . myClass CurrentData myClass.

+1

Source: https://habr.com/ru/post/1664619/


All Articles