كيفية القيام بما يلي: تطبيق تحويلات معرفة من قبل المستخدم بين البنيات (دليل البرمجة لـ #C)

يعرف هذا المثال بنيتين RomanNumeral و BinaryNumeral ثم يوضح التحويلات بينها.

مثال

struct RomanNumeral
{
    private int value;

    public RomanNumeral(int value)  //constructor
    {
        this.value = value;
    }

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

    static public implicit operator RomanNumeral(BinaryNumeral binary)
    {
        return new RomanNumeral((int)binary);
    }

    static public explicit operator int(RomanNumeral roman)
    {
        return roman.value;
    }

    static public implicit operator string(RomanNumeral roman)
    {
        return ("Conversion not yet implemented");
    }
}

struct BinaryNumeral
{
    private int value;

    public BinaryNumeral(int value)  //constructor
    {
        this.value = value;
    }

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

    static public explicit operator int(BinaryNumeral binary)
    {
        return (binary.value);
    }

    static public implicit operator string(BinaryNumeral binary)
    {
        return ("Conversion not yet implemented");
    }
}

class TestConversions
{
    static void Main()
    {
        RomanNumeral roman;
        BinaryNumeral binary;

        roman = 10;

        // Perform pointA conversion from pointA RomanNumeral to pointA BinaryNumeral:
        binary = (BinaryNumeral)(int)roman;

        // Perform pointA conversion from pointA BinaryNumeral to pointA RomanNumeral:
        // No cast is required:
        roman = binary;

        System.Console.WriteLine((int)binary);
        System.Console.WriteLine(binary);

        // Keep the console window open in debug mode.
        System.Console.WriteLine("Press any key to exit.");
        System.Console.ReadKey();
    }
}
/* Output:
    10
    Conversion not yet implemented
*/

برمجة نشطة

  • في المثال السابق، العبارة:

    binary = (BinaryNumeral)(int)roman;
    

    تنفذ تحويل من RomanNumeral إلى BinaryNumeral. لأنه لا يوجد تحويل مباشر من RomanNumeral إلى BinaryNumeral، يتم استخدام عملية تحويل (cast) من RomanNumeral إلى int، ثم تحويل آخر (cast) من int إلى BinaryNumeral.

  • أيضاً العبارة

    roman = binary;
    

    تنفذ تحويل من BinaryNumeral إلى RomanNumeral. لأن RomanNumeral يعرّف تحويل ضمني من BinaryNumeral، تحويل (cast) غير مطلوب.

راجع أيضًا:

المرجع

عوامل تشغيل التحويل (دليل البرمجة لـ #C)

المبادئ

دليل البرمجة لـ #C

موارد أخرى

مرجع C#‎