简体   繁体   English

泛型C#如何通过参数传递泛型对象的属性

[英]Generics C# How to pass a property of a generic object by parameter

I have created this method but it has a problem that I couldn't sort it out. 我已经创建了此方法,但是有一个我无法解决的问题。

How can I pass by parameter the predicate? 如何通过参数传递谓词? Because "x.IsActive" and "source.Id" and "x.Id" vary, normally all the objects I will pass by parameter have IsActive and Id properties. 因为“ x.IsActive”,“ source.Id”和“ x.Id”不同,所以通常我将通过参数传递的所有对象都具有IsActive和Id属性。

 public static Differences<T> CheckChanges<T>(List<T> sourceTable, List<T> destinationTable)
    {
        var differences = new Differences<T>();

        foreach (var sourceItem in sourceTable.Where(x => x.IsActive))
        {
            var destinationItem = destinationTable.FirstOrDefault(x => x.Id == sourceItem.Id);
        }

        return differences;
    }

If you can make all your objects inherit from a common interface, this could be much easier: 如果可以使所有对象都从一个公共接口继承,则可能会容易得多:

public interface IAccount
{
    int Id { get; set; }
    bool IsActive { get; set; }
}

Your method signature would look more like this then: 然后,您的方法签名将看起来像这样:

public static Differences<IAccount> CheckChanges(List<IAccount> sourceTable, List<IAccount> destinationTable)
public static Differences<T> CheckChanges<T>(List<T> sourceTable, 
                                             List<T> destinationTable, 
                                             Func<T, bool> predicate,
                                             Func<T, T, bool> pred2)
{
    var differences = new Differences<Account>();

    foreach (var sourceItem in sourceTable.Where(predicate))
    {
        var destinationItem = destinationTable.FirstOrDefault(x => pred2(x, sourceItem));
    }

    return differences;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM