在通用方法中传递/指定属性?

时间:2013-11-19 20:03:00

标签: c# .net generics func

我正在尝试将我编写的一些代码移动到更通用的方法中。虽然方法较长,但我遇到问题的部分如下:

public static void Test()

{    
           MyObjectType[] list1 = ListMyObjectTypeMethod1();
            MyObjectType[] list2 = ListMyObjectTypeMethod2();

            List<MyObjectType> linqAblelist1 = new List<MyObjectType>(list1);
            List<MyObjectType> linqAblelist2 = new List<MyObjectType>(list2);

            IEnumerable<MyObjectType> toBeAdded = linqAblelist1.Where(x => linqAblelist2.All(y => y.Property1 != x.Property1));
            IEnumerable<MyObjectType> toBeDeleted = linqAblelist2.Where(a => linqAblelist1.All(b => b.Property1 != a.Property1));

}

我正在尝试为MyObjectType传递一个泛型类型,但我在哪里[如何在这里设置属性?]如何在方法的参数中指定它?

public static void Test<T>(T[] x, T[] y)
        {
            List<T> list1 = new List<T>(x);
            List<T> list2 = new List<T>(y);
            IEnumerable<T> toBeAdded = list1.Where(x => list2.All(y => y.[How To Set Property Here?] != x.[How To Set Property Here?]));
            IEnumerable<T> toBeDeleted = list2.Where(a => list1.All(b => b.[How To Set Property Here?])); != a.[How To Set Property Here?]));));

        }

4 个答案:

答案 0 :(得分:10)

将选择的属性作为Func<T, TProperty>传递:

public static void Test<T, TProperty>(T[] x, T[] y, Func<T, TProperty> propertySelector)
    {
        List<T> list1 = new List<T>(x);
        List<T> list2 = new List<T>(y);
        IEnumerable<T> toBeAdded = list1.Where(x => list2.All(y => !propertySelector(y).Equals(propertySelector(x))));
        IEnumerable<T> toBeDeleted = list2.Where(a => !list1.All(b => propertySelector(b).Equals(propertySelector(a))));

    }

然后你可以通过为propertySelector指定lambda表达式来调用它:

Test(someArray, someOtherArray, t => t.SomeProperty);

答案 1 :(得分:1)

最佳选择是引入泛型类型约束,以确保T从特定类继承或实现接口。在任何一种情况下,类或接口都必须声明Property1。例如。像这样:

public static void Test<T>(T[] x, T[] y) where T : IHasProperty1
{
    …
}

答案 2 :(得分:0)

您需要对通用类型设置一些约束。

public static void Test<T>(T[] x, T[] y) where T : <SomeInterface>
{
   List<T> list1 = new List<T>(x);
   List<T> list2 = new List<T>(y);
   IEnumerable<T> toBeAdded = list1.Where(x => list2.All(y => y.PropertyName != x.PropertyName));
    IEnumerable<T> toBeDeleted = list2.Where(a => list1.All(b => b.PropertyName)); != a.PropertyName));));

}

答案 3 :(得分:0)

您可以添加一个通用约束,以确保T具有您期望的属性。类似的东西:

public static void Test<T>(T[] x, T[] y) where T : MyObjectType
{
    List<T> list1 = new List<T>(x);
    List<T> list2 = new List<T>(y);
    IEnumerable<T> toBeAdded = list1.Where(x => list2.All(y => y.Property1  != x.Property1 ));
    IEnumerable<T> toBeDeleted = list2.Where(a => list1.All(b => b.Property1 )); != a.[How To Set Property Here?]));));

}