在vb.net中是否有任何函数作为魔术方法__get()和__set()在php中的替代方法 [英] Is there any function in vb.net as an alternative to magic methods __get() and __set() in php

查看:168
本文介绍了在vb.net中是否有任何函数作为魔术方法__get()和__set()在php中的替代方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PHP有一些神奇的方法,比如 __ get() __ set()。在vb.net中有没有其他的选择。或者是否有任何其他的技巧可以完成呢?

PHP has magic methods like __get() and __set(). Is there any alternative for it in vb.net. Or is there any other tricks that can be done instead?

这就是我在php中完成的任务

This was what i done in php

private $data = array();

public function __construct($arData) {
    $data['var1'] = 'value1';
    $data['var2'] = 'value2';
    $data['var3'] = 'value3';
}

public function __get($propertyName) {
    if(!array_key_exists($propertyName, $this->data))
        throw new Exception("Invalid property");
    else
        return $this->data[$propertyName];
}

现在我可以访问实际不存在的属性,如 $ obj-> var1 $ obj-> var2 $ obj-> var3

Now i am able to access property that actually doesn't exist like $obj->var1, $obj->var2 and $obj->var3

这可以在VB.Net中完成吗?

Can this be done in VB .Net?

推荐答案

你可以实现一个私有字典来保留Property Name / Values对。类似于:

You can implement a private dictionary to keep Property Name/Values pairs. Something like:

Public Class myObj

    Private m_aProperties As Dictionary(Of String, String)

    Public Sub New()
        m_aProperties = New (Of String, String)
    End Sub

    Public Function __Get(i_sPropName As String) As String

        If m_aProperties.ContainsKey(i_sPropName) Then
            Return m_aProperties(i_sPropName)
        Else
            Return String.Empty
        End If

    End Function

    Public Sub __Set(i_sPropName As String, i_sPropValue As String)

        If m_aProperties.ContainsKey(i_sPropName) Then
            m_aProperties(i_sPropName) = i_sPropValue
        Else
            m_aProperties.Add(i_sPropName, i_sPropValue)
        End If

    End Sub
End Class

如果该属性不存在,它将在字典中创建一个新条目。如果您尝试返回一个不存在的属性,它将返回一个空字符串。使用示例:

It would create a new entry in dictionary if the property doesn't exist. It will return an empty string if you attempt to return a non-existing property. Example of usage:

    Dim myObj1 As New myObj

    myObj1.__Set("aaa", "123")
    Dim s As String = myObj1.__Get("aaa")

可以扩展为适用于不同的数据类型,以不同的方式处理不存在的属性等。但是,在运行时创建属性的基本概念是保持它不受限制。

This can be expanded to work for different data types, to handle non-existing properties differently etc. But the basic concept to create property at runtime is to keep it in a dictonary.

这篇关于在vb.net中是否有任何函数作为魔术方法__get()和__set()在php中的替代方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆