簡體   English   中英

如何在c#中賦值后保留有關對象的信息?

[英]How can I persist information about an object after assignment in c#?

我一直在問我認為可能是什么解決方案的問題 ,但有人指出我陷入了XY問題,我應該問一下我的確切問題。

我有一個結構,我希望其他人能夠在他們自己的程序中使用。 它需要可以從其他現有類型隱式轉換為此類型,但同時在分配后需要保留一些信息。 這是一個簡單的問題示例:

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);
    }
}

使用隱式轉換中的新結構替換結構后,存儲在SomethingImportant的信息將丟失。 這將是重載賦值運算符的自然位置,但不幸的是,這在c#中是不可能的。

我的想法轉向了屬性,因為在對象的初始聲明之后不需要修改額外的信息,如果持久性僅限於類的字段,那么它將是最可接受的。 看起來這不是一個可行的選擇,因為結構不能訪問與之關聯的屬性,除非它知道它所在的類型。

有沒有辦法在c#中像這樣遠程完成某些事情? 我知道添加像MyStruct.Update(double x)這樣的顯式更新函數會產生所需的行為,但是,根據庫的運行方式,這將對用戶重寫大量現有代碼帶來巨大負擔。 我寧願在我自己的代碼中做一些雜亂,不安全或模糊的事情,而不是需要對圖書館用戶進行如此多的重寫。

謝謝你的任何想法!

我認為這根本不可能,因為對於所有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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM