Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在数组中查找接口的特定实现,并移动到数组的顶部_C# - Fatal编程技术网

C# 在数组中查找接口的特定实现,并移动到数组的顶部

C# 在数组中查找接口的特定实现,并移动到数组的顶部,c#,C#,我有一个接口ITestInterface,在同一个程序集中有该接口的默认实现。现在,依赖DLL可以实现这个接口,并通过IoC容器注册实现 在我的程序集中,当应用程序启动时,我使用IoC容器将所有实现放入一个数组中。现在,如何确保程序集中的默认实现移动到实现数组的顶部?List implementations=GetImplementationsFromIoc(); List<ITestInterface> implementations = GetImplementationsFro

我有一个接口
ITestInterface
,在同一个程序集中有该接口的默认实现。现在,依赖DLL可以实现这个接口,并通过IoC容器注册实现

在我的程序集中,当应用程序启动时,我使用IoC容器将所有实现放入一个数组中。现在,如何确保程序集中的默认实现移动到实现数组的顶部?

List implementations=GetImplementationsFromIoc();
List<ITestInterface> implementations = GetImplementationsFromIoc();
implementations = implementations
    .OrderByDescending(i => i.GetType() == typeof(MyDefaultImplementation))
    .ToList();
实现=实现 .OrderByDescending(i=>i.GetType()==typeof(MyDefaultImplementation)) .ToList();
其实很简单。一旦你有了你的列表,搜索它来寻找你的实现,然后首先交换它

List<ITestInterface> implementations = GetImplementationsFromIoc();

// find your implementation
var index = implementations.FindIndex(impl => impl is MyDeFaultImplementation);

//make sure your implementation is truely there!
if(index != -1)
{
    //swap your implementation on top of the list
    var myImpl = implementations[index];
    implementations[index] = implementations[0];
    implementations[0] = myImpl;
}
List implementations=GetImplementationsFromIoc();
//找到您的实现
var index=implements.FindIndex(impl=>impl是MyDeFaultImplementation);
//确保您的实现是真实的!
如果(索引!=-1)
{
//交换列表顶部的实现
var myImpl=实现[索引];
实现[索引]=实现[0];
实现[0]=myImpl;
}

无论如何,我有一种不好的感觉,你必须先有一个特定的实现。如果我是你,我会仔细看看我的体系结构和依赖注入的使用。

你有一些代码要展示吗?你甚至可以保证你的实现会在列表中吗?一般来说(你可能知道),你可以询问引用的对象是否属于某一类型。由于您知道默认实现的确切类型,因此可以测试数组中的每个元素,如果找到,则将其移动到顶部,方法是在数组中复制元素,或者临时创建一个列表并返回到数组(如果不过分)。
i.GetType()==typeof(MyDefaultImplementation)
对于
我是MyDefaultImplementation
来说有点过分了,除非OP认为人们会继承
MyDefaultImplementation
(通常不太可能,如果你不想让类密封和/或内部的话,这是可以避免的)。@Falanwe:是的,我追求的是正确性,而不是性能。由于不知道默认实现是否是密封的,我对使用
is
感到不舒服。这里的LINQ可能比
==typeof()
更贵。我同意,这个LINQ看起来相当贵。也会产生无用的副本,
OrderByDescending
也不是真正最快的LINQ方法(它在内部创建一个索引“列表”,并且必须对每个元素求值谓词,这可能会累加起来)。通常这并不重要,但我觉得LINQ在这里不是一个解决方案,你可以通过简单的
List
操作做得更好(非常不寻常,LINQ通常是一个非常好的解决方案)。@Falanwe:我认为LINQ在这里是一个非常合理的工具。它简短易读,易于维护。另外,它没有副作用。就性能而言,此代码将在应用程序的生命周期中运行一次,并且可能只会增加几纳秒的处理时间,因此为了避免处理成本过早优化而使其复杂化。我完全不同意。找到正确的索引是对
List
方法的一个非常简单的调用,从列表中交换两个元素非常简单,每个拥有一个编程类的程序员都知道如何做。我觉得是林克让事情复杂化了,而不是相反。不过,我确实同意,性能的变化可能并不重要。