我一直在问我的想法可能是解决方案 https://stackoverflow.com/questions/35254467/is-it-possible-in-c-sharp-to-get-the-attributes-attached-to-a-property-from-with,但有人指出我陷入了 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;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)