【问题标题】:Multiple Overloaded Extension Methods in C#C# 中的多个重载扩展方法
【发布时间】:2015-01-24 00:00:00
【问题描述】:

使用重载的扩展方法设置数据时遇到问题 -

我有两种扩展方法:

public static void Fill(this SearchRequest request, ISearchViewModel vm)
{
    request.blabla = vm.blabla;
}

public static void Fill(this IEnumerable<IViewModel> response, SearchResponse searchResponse)
{
 // a list is created here and assigned to response
  List<IViewModel> someResults = new List<IViewModel>();
 // do stuff with search response and someResults
 response = someResults;
}

我第一次打电话:

 SearchRequest request = new SearchRequest ();
 request.Fill(criteria);

并且 request.blabla 按预期设置。到目前为止一切顺利。

然后我试试:

ResultViewModel result = new ResultViewModel ();
result.searchResult.Fill(searchResponse);

.searchResult 是 IViewModel 的一个 IEnumerable,但是在调用 Fill 行之后,result.searchResult 为 null。肯定是调用了填充扩展方法,肯定是在设置数据。

任何关于可能出错的想法将不胜感激。

(我使用的是 VS 2015,这是一个 vNext 项目 - 不是那些不是真正的变量/类名)

【问题讨论】:

  • 我建议你使用你编译的真实代码。使用Main 方法的简短且独立的示例将是理想的。
  • 第二个扩展方法的参数重复了response。将您用于分配的代码放入响应(第一个参数)
  • 当您说某些东西不起作用时,让我们看看。使用发布的伪代码,我们不能轻易提供帮助。发布不起作用的实际代码。或者至少是不起作用的代码(MVCE)。
  • @rejnev - 我已经更新了问题,如果不清楚,抱歉。
  • @Azat - 我已经稍微更新了代码。结果是明确定义的。在调用 Fill 之前,我还尝试将 result.searchResult 设置为一个新的空列表。它回来是空的。

标签: c# extension-methods asp.net-core


【解决方案1】:

responseresult.searchResult,它不是那个变量 的别名。将值设置为 response 不会改变 result.searchResult。没有办法编写通过引用而不是值传递其隐式参数的扩展方法。

【讨论】:

  • 谢谢。这是有道理且有效的。我认为它的工作方式与第一种方法相同,无论它是一个属性。
【解决方案2】:

IEnumerables 是不可变的。也许您可以将类型更改为像 List 这样的可变类型?

【讨论】:

  • 感谢您的建议,但是使用列表不起作用。它也是空的。 Servy 上面的回答解释了这一点。
【解决方案3】:

您可以使用此代码代替您的代码:

void Main()
{
    var f=new Foo();
    f.FillMyList();
}

public class Foo
{
    public List<string> MyList { get; set; }
}

public static class extensions
{
    public static void FillMyList(this Foo f)
    {
        f.MyList=new List<string>();
        f.MyList.Add("some item");
    }
}

【讨论】:

  • 谢谢,我现在也有类似的东西。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-23
  • 2012-06-15
  • 1970-01-01
  • 1970-01-01
  • 2013-04-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多