c# - 如何订购 2 个不同的列表?

标签 c#

我有一个 Step 类和一个 AutoStep

class Step {
    int StepNumber;
}

class AutoStep {
    int StepNumber;
}

它们不能继承自任何类并且不能继承自任何类。

我必须按 StepNumber 对它们进行排序,并根据它们的类型(StepAutoStep)调用特定方法

我该怎么做?

最佳答案

从字面上看,这就是接口(interface)的用途:

public interface ISteppable
{
    public int StepNumber { get; }
    public void Foo();//the method you need to call; adjust the signature as needed
}

class step : ISteppable
{
    int StepNumber;

    int ISteppable.StepNumber
    {
        get { return StepNumber; }
    }

    public void Foo()
    {

    }
}

class AutoStep
{
    int StepNumber;

    int ISteppable.StepNumber
    {
        get { return StepNumber; }
    }

    public void Foo()
    {

    }
}

然后您可以创建一个 ISteppable 对象的集合,并使用它们的 StepNumber 属性对它们进行排序,并对每个对象调用 Foo

由于您无法修改任何一个类,因此您需要使用适配器模式为这些类型创建这些接口(interface)的实现:

public class StepAdapter : ISteppable
{
    private step value;
    public StepAdapter(step value)
    {
        this.value = value;
    }

    public int StepNumber
    {
        get { return value.StepNumber; }
    }

    public void Foo()
    {
        value.Foo();
    }
}

public class AutoStepAdapter : ISteppable
{
    private AutoStep value;
    public AutoStepAdapter(AutoStep value)
    {
        this.value = value;
    }

    public int StepNumber
    {
        get { return value.StepNumber; }
    }

    public void Foo()
    {
        value.Foo();
    }
}

然后您可以创建一个 ISteppable 对象的集合,当您想要添加一个 step 对象时,只需将它包装在一个 StepAdapter 中并将所有 AutoStep 对象包装在 AutoStepAdapter 对象中。

List<ISteppable> list = new List<ISteppable>();

list.Add(new StepAdapter(new step(){StepNumber = 5}));
list.Add(new AutoStepAdapter(new AutoStep(){StepNumber = 3}));

list.Sort((a, b) => a.StepNumber.CompareTo(b.StepNumber));

foreach (var item in list)
{
    item.Foo();
}

关于c# - 如何订购 2 个不同的列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14217801/

相关文章:

c# - QueryOver 集合包含所有值

c# - 配置文件引用错误位置的 .Net 应用程序

c# - 如何在 C# 3.5 的父类(super class)中定义强制转换运算符?

c# - IEnumerable 重复函数

c# - PostSharp - il 编织 - 想法

c# - 当我们指定了类的访问说明符时,是否有任何约束来指定类成员的访问说明符?

c# - 如何使用 Microsoft.Build.Evaluation.Project.RemoveItem

c# - 从字符串 EOT 逗号 ETX 中删除控制字符序列

c# - XElement.Parse NotSuportedException

c# - 如何使用 LINQ to XML 查询日期时间值?