简体   繁体   English

扩展方法未分配值

[英]Extention method not assigning value

I have a custom sort method for my dataset. 我对数据集有一个自定义排序方法。 I call it like this: 我这样称呼它:

ds.Sort("column"); ds.Sort(“ column”);

where ds is of type dataset. ds是数据集类型。 Then I sort the first table (sorting code itself is not relevant as the breakpoint shows the result is correct). 然后,我对第一个表进行排序(排序代码本身不相关,因为断点表明结果正确)。 My sort method looks like this: 我的排序方法如下所示:

public static void Sort(this DataSet ds, string column)
{
    DataSet newDs = ds.Copy();

    //sorting occurs

    ds = newDs.Copy();
} // <- breakpoint

At the place of breakpoint both ds and newDs have everything sorted like it should. ds和newD都在断点处对所有内容进行了应有的排序。 However once I move forward and get to the line after calling this sort method, ds is no longer sorted. 但是,一旦我继续前进并在调用此sort方法后到达该行,ds将不再进行排序。 I also tried the same with simply doing 我也做了简单的尝试

ds.Clear(); 

in that Sort method and this time it worked. 在那个排序方法中,这次它起作用了。 Am I not allowed to assign a value to the object? 我不允许为该对象分配值吗? Is it possible to do this in some way? 是否可以通过某种方式做到这一点?

Am I not allowed to assign a value to the object? 我不允许为该对象分配值吗?

You're not assigning a value to an object . 您没有为对象分配值。 You're assigning a value to a variable ... and that variable is a parameter. 您正在为变量分配一个值...而该变量是一个参数。 Changes to that parameter value are not seen outside the method, as C# uses pass-by-value by default. 在方法外部看不到对该参数值的更改,因为C#默认情况下使用值传递。 So for example, consider this code: 因此,例如,考虑以下代码:

static void Foo(string input)
{
    input = "In Foo";
}
...
string text = "hello";
Foo(text);
Console.WriteLine(text); // Still prints "hello"

If you don't understand that, read my article on parameter passing for more details. 如果您不了解,请阅读我有关参数传递的文章以获取更多详细信息。

You probably want something like this: 您可能想要这样的东西:

public static DataSet CopyAndSort(this DataSet ds, string column)
{
    DataSet newDs = ds.Copy();

    //sorting occurs
    return newDs; // No need to copy it *again*.
}

Then you can use: 然后,您可以使用:

ds = ds.CopyAndSort("column");

The difference between 和...之间的不同

ds.Clear();

and

ds = newDs.Copy();

is that the first operates on the DataSet object that you have passed in through a reference ds , while the second one re-assigns a new object to that variable, making the original object inaccessible to your extension method. 是第一个操作对您通过引用ds传入的DataSet对象进行操作,而第二个操作将新对象重新分配给该变量,从而使扩展方法无法访问原始对象。

You can use Merge method as a backdoor for filling the original data set with sorted data: 您可以将Merge方法用作后门,以使用排序后的数据填充原始数据集:

ds.Reset();
ds.Merge(newDs);

This will work, because the data would be copied into the original DataSet . 这将起作用,因为数据将被复制到原始DataSet

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM