1

我正在尝试概括我编写的解决方案,以便可以将其应用于类似的问题。

我有许多不同的对象,它们都包含可为空的双精度数。我想以某种方式将它们(双打)传递到字典中,然后将数据直接放入相关对象中。

如果双打是引用类型,这将非常简单,但它们不是。

所以我需要一个通过引用来引用它们的解决方案。我唯一能想到的就是创建我自己的包含双精度类型的类,但这需要大量工作,因为我使用了许多双精度类型的代码——据我所知,你不能扩展值类型。

关于我如何去做的任何想法?

添加 - 这是我正在尝试做的事情的示例代码示例。这不是实际的代码。

void ReadTable(Dictionary<string,double?> dict)
{
//read some sort of table here by usign the string as the headers
dict["header"] = Convert.toDouble(tableValue);
//etc...
}

MyObject myObject = new MyObject();
//fill it up from the table
Dictionary<string,double?> req = new Dictionary<string,double?>();
req.add("header",myObject.something);
req.add("header2",myObject.somethingElse);
ReadTable(req);

MyOtherObject myOtherObject = new MyOtherObject();
//fill it up from the table
Dictionary<string,double?> req2 = new Dictionary<string,double?>();
req2.add("aheader",myOtherObject.m2something);
req2.add("aheader2",myOtherObject.m2somethingElse);
ReadTable(req2);
4

1 回答 1

2

如果您的意图是(非编译代码,仅用于说明):

Dictionary<string, ref double?> lookup = ...

double? someField = ...

lookup.Add("foo", ref someField);

然后:

lookup["foo"] = 123.45;

并让那些知道的代码出现someField:那么确实,那不能也不会起作用。好吧,有一些疯狂的hacky方法,但不要那样做。您所描述的确实是正确的方法:

public class MyWrapper {
    public double? Value {get;set;}
}

Dictionary<string, MyWrapper> lookup = ...

MyWrapper someField = new MyWrapper();

lookup.Add("foo", someField);

然后:

lookup["foo"].Value = 123.45;

然后任何代码引用someField.Value都会看到新值。

您也许可以使用泛型来概括这一点。

如果您想最小化代码更改,您可以添加一个运算符:

public class MyWrapper {
    public double? Value {get;set;}
    public static implicit operator double?(MyWrapper value) {
        return value == null ? null : value.Value;
    }
}

这至少适用于执行以下操作的任何代码:

double? tmp = someField;

或者:

SomeMethodThatTakesNullableDouble(someField);
于 2012-08-01T09:24:28.843 回答