The default value is "value" in primitive types

primitive types (integer, string, etc.) are now classes. However, to access the value of the class, you simply use the name of the object (ex, x = y). There is no need to refer to a class property (x.value = y.value).

To implement an abstract data class (e.g. inches), we need the value property, so if we have dim x as inches (our class) we should use: x.value = 3

is that honest

+5
source share
3 answers

You have the option to overload the assignment operator to suit your needs.

For example:

public static implicit operator Inches(int value)
{
   return new Inches(value);
}

At this point, you can do something like this:

Inches something = 4;
+6
source

, . #, VB.Net( )

Class Inches
    Private _value As Integer
    Public ReadOnly Property Value() As Integer
        Get
            Return _value
        End Get
    End Property
    Public Sub New(ByVal x As Integer)
        _value = x
    End Sub

    Public Shared Widening Operator CType(ByVal x As Integer) As Inches
        Return New Inches(x)
    End Operator

    Public Shared Widening Operator CType(ByVal x As Inches) As Integer
        Return x.Value
    End Operator
End Class

    Dim x As Inches = 42
    Dim y As Integer = x
+6

Another example:


class Program
{
    class A
    {
        private int _x;
        public A(int x)
        {
            _x = x;
        }

        public static implicit operator int(A a)
        {
            return a._x;
        }
    }
    static void Main(string[] args)
    {
        A a = new A(3);
        Console.WriteLine(a);
    }
}

0
source

All Articles