使包装器类的扩展方法/构造函数泛型

本文关键字:方法 构造函数 泛型 扩展 包装 | 更新日期: 2023-09-27 18:14:22

在一个服务(,我不能改变)我有两个对象类BarBaz大多相似的属性(,但遗憾的是没有,他们不派生自相同的基类或继承自相同的接口…是的——哑巴),以及与其相关的BarQuxBazQux属性相关的依赖类:

public class Bar                          public class Baz
{                                         {
    public int ID { get; set; }               public int ID { get; set; }
    public bool Active { get; set; }          public bool Active { get; set; }
    public int BarQux { get; set; }           public int BazQux { get; set; }
    ...                                       ...
}                                         }
public class Qux
{
    public int ID { get; set; } // Corresponds to BarQux and BazQux
    public string Name { get; set; }
}

在WPF屏幕中,我将每种类型(BazBar)的列表绑定到两个单独的ListViews。我需要每个有一个额外的Selected复选框列。为此,我创建了一个包装器类,其中包含常用属性、附加的Selected属性和每个属性的构造函数:

public class Foo
{
    public Foo(Bar bar, Qux qux)
    {
        this.Active = bar.Active;
        this.FooQux = string.Format("{0} - {1}", qux.ID, qux.Name);
        ...
    }
    public Foo(Baz baz, Qux qux)
    {
        this.Active = baz.Active;
        this.FooQux = string.Format("{0} - {1}", qux.ID, qux.Name);
        ...
    }
    public bool Selected { get; set; }
    public int ID { get; set; }
    public bool Active { get; set; }
    public string FooQux { get; set; }
    ...
}
为了将BazBar类的集合转换为Foo的集合,我创建了以下扩展方法:
public static List<Foo> ToFoo(this IEnumerable<Bar> bars, IEnumerable<Qux> quxs)
{
    List<Foo> foos = new List<Foo>();
    foreach (Bar bar in bars)
    {
        Foo foo = new Foo(bar, quxs.Single(qux => qux.ID == bar.BarQux));
        foos.Add(foo);
    }
    return foos;
}
public static List<Foo> ToFoo(this IEnumerable<Baz> bazs, IEnumerable<Qux> quxs)
{
    List<Foo> foos = new List<Foo>();
    foreach (Baz baz in bazs)
    {
        Foo foo = new Foo(baz, quxs.Single(qux => qux.ID == baz.BazQux));
        foos.Add(foo);
    }
    return foos;
}

问题:

如何使其泛型?

理论、实现和错误:

  1. 由于构造函数除了BarBaz参数之外几乎是相同的,我可以以某种方式使用泛型T来创建一个构造函数并且仍然抓取属性吗?

    public class Foo<T>
    {
        public Foo(T obj, Qux qux)
        {
            this.Active = obj.Active; // 'T' does not contain a definition for 'Active'...
            this.Qux = string.Format("{0} - {1}", qux.ID, qux.Name);
            ...
        }
        ...
    }
    
  2. 更改构造函数以接收Qux对象的整个集合并在那里执行quxs.Single(qux => qux.ID == object.ObjectQux)逻辑。然后将这些扩展方法做成一个泛型方法,如下所示。

    public static List<Foo> ToFoo<T>(this IEnumerable<T> objCollection, IEnumerable<Qux> quxs)
    {
        List<Foo> foos = new List<Foo>();
        foreach (T obj in objCollection)
        {
            Foo foo = new Foo(obj, quxs); // The best overloaded method... has some invalid arguments.
            foos.Add(foo);
        }
        return foos;
    }
    
  3. 1和2组合?还有我没想到的吗?

使包装器类的扩展方法/构造函数泛型

如果您的属性有限,并且列表中的项目数量也很少,那么您可以使用Reflection。由于您将在WPF中使用此功能,我还建议将该进程移动到单独的后台线程中。

通用Foo

public class Foo<T>
{
    public Foo(T obj, Qux qux)
    {
        //this.Active = obj.Active;
        var fooProps = GetType().GetProperties().ToList();
        var tProps = typeof(T).GetProperties()
            .Where(p =>
            {
                var w = fooProps.FirstOrDefault(f => f.Name == p.Name);
                return w != null;
            }).ToList();
        foreach (var propertyInfo in tProps)
        {
            var val = propertyInfo.GetValue(obj);
            fooProps.First(e => e.Name == propertyInfo.Name).SetValue(this, val);
        }
        this.FooQux = string.Format("{0} - {1}", qux.ID, qux.Name);
    }
    public bool Selected { get; set; }
    public int ID { get; set; }
    public bool Active { get; set; }
    public string FooQux { get; set; }
}

扩展方法

    public static IEnumerable<Foo<Bar>> ToFoo(this IEnumerable<Bar> bars, IEnumerable<Qux> quxs)
    {
        return bars.
            Select(bar => new Foo<Bar>(bar, quxs.Single(qux => qux.ID == bar.BarQux))).ToList();
    }
    public static IEnumerable<Foo<Baz>> ToFoo(this IEnumerable<Baz> bazs, IEnumerable<Qux> quxs)
    {
        return bazs.
            Select(baz => new Foo<Baz>(baz, quxs.Single(qux => qux.ID == baz.BazQux))).ToList();
    }
    public static IEnumerable<Qux> ToQuxes(this IEnumerable<BazQux> bazQuxs)
    {
        return bazQuxs.Select(b => new Qux(typeof(BazQux), b)).ToList();
    }
    public static IEnumerable<Qux> ToQuxes(this IEnumerable<BarQux> barQuxes )
    {
        return barQuxes.Select(b => new Qux(typeof(BarQux), b)).ToList();
    }

同样,您也可以将BarQuxBazQux转换为非泛型Qux类。

public class Qux
{
    public int ID { get; set; } // Corresponds to BarQux and BazQux
    public string Name { get; set; }
    public Qux(Type type, object obj)
    {
        var ob = Convert.ChangeType(obj, type);
        var quxProps = GetType().GetProperties();
        var obProps = ob.GetType().GetProperties()
            .Where(p =>
            {
                var w = quxProps.FirstOrDefault(f => f.Name == p.Name);
                return w != null;
            }).ToList();
        foreach (var propertyInfo in obProps)
        {
            var val = propertyInfo.GetValue(obj);
            quxProps.First(e => e.Name == propertyInfo.Name).SetValue(this, val);
        }
    }
}

你可以调用ToFoo扩展方法,瞧,你有一个Foo列表。

您还可以使用Qux

的逻辑将Foo转换为非泛型

我真的看不出这样做有什么好处。

如果你坚持使用泛型,你可以对T做一些类型检查,像这样:

public class Foo<T>
{
    public Foo(T obj, Qux qux)
    {
        var baz = obj as Baz;
        var bar = obj as Bar;
        Active = baz != null && baz.Active || bar != null && bar.Active;
        this.FooQux = string.Format("{0} - {1}", qux.ID, qux.Name);
    }
    public bool Selected { get; set; }
    public int ID { get; set; }
    public bool Active { get; set; }
    public string FooQux { get; set; }
}

或:

public static List<Foo> ToFoo<T>(this IEnumerable<T> objCollection, IEnumerable<Qux> quxs)
{
    List<Foo> foos = new List<Foo>();
    foreach (T obj in objCollection)
    {
        var baz = obj as Baz;
        var bar = obj as Bar;
        Foo foo = null;
        if(baz != null)
            foo = new Foo(baz, quxs.Single(qux => qux.ID == baz.BazQux));
        if(bar != null)
            foo = new Foo(bar, quxs.Single(qux => qux.ID == bar.BarQux));
        if(foo != null)
            foos.Add(foo);
    }
    return foos;
}

但是这显然并不比你已经拥有的好多少,如果T不是Bar或Baz(没有显示),你将不得不做一些异常处理,这将使你暴露于潜在的运行时失败。你也可以使用反射,但效果是一样的。

你正在寻找不幸的是c#是不可能的。唯一可以避免这种情况的方法是,如果界面是像Golang一样的duck-typed,但情况并非如此。

根据Sandesh的建议,最终结果:

public class Foo<T>
{
    public Foo() {}
    public Foo(T obj, IEnumerable<Qux> quxs, string quxPropName)
    {
        var fooProps = GetType().GetProperties().ToList();
        var tProps = typeof(T).GetProperties()
            .Where(p =>
            {
                var w = fooProps.FirstOrDefault(f => f.Name == p.Name);
                return w != null;
            }).ToList();
        foreach (var propertyInfo in tProps)
        {
            var val = propertyInfo.GetValue(obj, null);
            fooProps.First(e => e.Name == propertyInfo.Name).SetValue(this, val, null);
        }
        int id = (int)typeof(T).GetProperty(quxPropName).GetValue(obj, null);
        Qux qux = quxs.Single(q => q.ID == id);
        this.FooQux = string.Format("{0} - {1}", qux.ID, qux.Name);
    }
    public bool Selected { get; set; }
    public int ID { get; set; }
    public bool Active { get; set; }
    public string FooQux { get; set; }
}

和泛型扩展方法:

public static List<Foo<T>> ToFoo<T>(this IEnumerable<T> list, IEnumerable<Qux> quxs, string quxPropName)
{
    List<Foo<T>> foos = null;
    try
    {
        foos = list.Select(obj => new Foo<T>(obj, quxs, quxPropName)).ToList();
    }
    catch
    {
        foos = new List<Foo<T>>();
    }
    return foos;
}

和用法:

List<Foo<Bar>> bars = barCollection.ToFoo(quxCollection, "BarQux");
List<Foo<Baz>> bazs = bazCollection.ToFoo(quxCollection, "BazQux");