【发布时间】:2016-05-17 07:19:50
【问题描述】:
我一直在问我的想法might be solutions,但有人指出我陷入了 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) 这样的显式更新函数会提供所需的行为,但是根据库的功能,这对于重写大量现有代码的用户来说将是一个巨大的负担。我宁愿在自己的代码中做一些凌乱、不安全或晦涩难懂的事情,也不愿需要为图书馆用户进行如此多的重写。
感谢您的任何想法!
【问题讨论】:
-
由于
child是一个对象引用,而不是实际对象,我看不出有一种明显的方法可以使=的行为符合您对隐式转换的期望。
标签: c# attributes persistence variable-assignment