如何在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;