访问通用对象的属性

时间:2014-06-08 08:37:01

标签: c# generics

我有远程上下文,我知道这个上下文中的类具有相同的结构。我想避免为每个类创建方法。 实施例

public IEnumerable<CommonPersonFeatureValue> GetRegulation()
{
    var query = from c in remoteContext.RegulaminDaneOsobowe
        select new CommonPersonFeatureValue
        {
            PersonId = c.PersonId ?? 0,
            Crated = c.Created ?? DateTime.MinValue,
            CurStatus = String.IsNullOrEmpty(c.CurStatus) ? c.CurStatus : String.Empty,
            NewStatus = String.IsNullOrEmpty(c.NewStatus) ? c.NewStatus : String.Empty,
            Modified = c.Modified ?? DateTime.MinValue
        };

    return query;
}

public IEnumerable<CommonPersonFeatureValue> GetNDA()
{
    var query = from c in remoteContext.NDA
         select new CommonPersonFeatureValue
         {
             PersonId = c.PersonId ?? 0,
             Crated = c.Created ?? DateTime.MinValue,
             CurStatus = String.IsNullOrEmpty(c.CurStatus) ? c.CurStatus : String.Empty,
             NewStatus = String.IsNullOrEmpty(c.NewStatus) ? c.NewStatus : String.Empty,
             Modified = c.Modified ?? DateTime.MinValue
         };

    return query;
}

是否可以创建这样的方法

public IEnumerable<CommonPersonFeatureValue> GetCommonPersonFeatureValue<T>(this System.Data.Services.Client.DataServiceQuery<T> items)

问题在于我不知道如何正确访问通用对象的属性。一种解决方案是使用此代码

string newStatus = item.GetType().GetProperty("NewStatus").GetValue(item) as string

但我认为这是一种微弱的方法。您是否有更好的解决方案可以用一种常用方法替换这两种方法?

1 个答案:

答案 0 :(得分:1)

如果您可以使RegulaminDaneOsoboweNDA个对象实现一个公共接口(例如IThing),那么您的方法将获取接口的集合:

public IEnumerable<CommonPersonFeatureValue> QueryThings<TThing>(IQueryable<TThing> things)
    where TThing : IThing
{
    var query = from c in things
                select new CommonPersonFeatureValue
                {
                    PersonId = c.PersonId ?? 0,
                    Created = c.Created ?? DateTime.MinValue,
                    CurStatus = String.IsNullOrEmpty(c.CurStatus) ? c.CurStatus : String.Empty,
                    NewStatus = String.IsNullOrEmpty(c.NewStatus) ? c.NewStatus : String.Empty,
                    Modified = c.Modified ?? DateTime.MinValue
                };
    return query;
}

这可以称为

var ndaQuery = QueryThings(remoteContext.NDA);
var regulaminDaneOsoboweQuery = QueryThings(remoteContext.RegulaminDaneOsobowe);