How can I save object information after assignment in C #?

I asked questions about what I think might be the solution , but someone pointed out that I am getting into the XY problem and that I should just ask about my exact problem.

I have a structure that I want other people to use in their programs. It is necessary to be able to implicitly convert this type from other existing types, but at the same time, some information must be stored after this assignment. Here is a simple example of a problem:

using System;
public struct MyStruct {
    public string SomethingImportant;
    public MyStruct(string s) {
        SomethingImportant = s;
    }

    //this function needs to have no knowledge of how/where the struct is being used
    public bool SomeFunction(string s) {
        return s == SomethingImportant;
    }

    public static implicit operator MyStruct(double x) {
        return new MyStruct();
    }
}
public class MyClass {
    MyStruct child = new MyStruct("important");

    public MyClass() {
        //prints out "important"
        Console.WriteLine(child.SomethingImportant);
        child = 7.5;
        //prints out ""
        Console.WriteLine(child.SomethingImportant);
    }
}

After the structure is replaced with a new structure from an implicit conversion, the information stored in SomethingImportantwill be lost. This would be a natural place to overload the assignment operator, but unfortunately this is not possible in C #.

, , , . , , , , .

- , #? , , MyStruct.Update(double x), , , , , . - , , .

!

+4
1

, , , "- " MyStruct ( , static).

, , . , .

, , , , .

, :

public class MyClass
{
    public MyClass() 
    {
        MyStruct child1 = new MyStruct( "abc" );
        // should print "abc"
        Console.WriteLine(child1.SomethingImportant);

        MyStruct child2 = 7.5;
        // should print out what?
        Console.WriteLine(child2.SomethingImportant);

        MyStruct child3 = new MyStruct( "cde" );
        child3 = 5.7;
        // will never, ever print "cde" (if not static)
        Console.WriteLine(child2.SomethingImportant);
    }
}

:

public MyOtherClass
{
    public MyStruct TheChild;
    public string SomethingImportantAssociatedToTheChild;
}

[...]

MyOtherClass a;
a.SomethingImportantAssociatedToTheChild = "abc";
a.TheChild = 7.5;
0

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


All Articles