Что нового
  • Что бы вступить в ряды "Принятый кодер" Вам нужно:
    Написать 10 полезных сообщений или тем и Получить 10 симпатий.
    Для того кто не хочет терять время,может пожертвовать средства для поддержки сервеса, и вступить в ряды VIP на месяц, дополнительная информация в лс.

  • Пользаватели которые будут спамить, уходят в бан без предупреждения. Спам сообщения определяется администрацией и модератором.

  • Гость, Что бы Вы хотели увидеть на нашем Форуме? Изложить свои идеи и пожелания по улучшению форума Вы можете поделиться с нами здесь. ----> Перейдите сюда
  • Все пользователи не прошедшие проверку электронной почты будут заблокированы. Все вопросы с разблокировкой обращайтесь по адресу электронной почте : info@guardianelinks.com . Не пришло сообщение о проверке или о сбросе также сообщите нам.

Property accessor overloading: bypassing private properties

Lomanu4

Команда форума
Администратор
Регистрация
1 Мар 2015
Сообщения
11,703
Баллы
155
In TypeScript, a parent class can declare a private property like this:


abstract class Test {
private data: string;
}

Although a child class cannot access this property directly, it can still do so using a getter method:


abstract class Test {
private data: string;

// Getter method
public getData() { return this.data };
}

Wouldn't it be awesome if you could use property accessor overloading to read the property instead?


abstract class Test {
private data: string;
...

// Property accessor overloading
public data() {
return this.data;
}
}

Or even better


abstract class Test {
private data: string;
...

// Property accessor overloading
public get data() {
return this.data;
}
}

Unfortunately, this is not possible in TypeScript.
Attempting it will result in a TS2300: Duplicate identifier 'data' error.

In PHP, however, this can be achieved using the magic methods __get and __set:


class Test
{
private string $data = "Hello, World!";

public function __get(string $name) {
return $this->$name;
}

public function __set(string $name, $value) {
$this->$name = $value;
}
}

And you could then use the Test object to retrieve the private property:


$test = new Test();

$test->data; // Returns "Hello, World!"

// Override the data property
$test->data = "New value";

This is a clear demonstration of property accessor overloading. It makes sense because you might want to at least read the property, even if it is private. However, using accessor overloading to modify a private property could be considered bad practice in some cases, as it undermines encapsulation.

In C#, you can achieve similar behavior using the indexer feature or explicit properties with the get and set accessors. Here's how it works:


class Test
{
private string data = "Hello, World!";

public object this[string property]
{
get => data;
set => data = value as string;
}
}

Now, you can access data as if it were a dynamic property:


Test test = new Test();

test["data"]; // Returns "Hello, World!"

// Override the data property
test["data"] = "New value";

Unlike TypeScript, C# allows this kind of property accessor overloading using indexers. While this approach works, it should be used with caution, as it can reduce code clarity, or even defeat the purpose of encapsulation in private properties.


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

 
Вверх