Serialize only those properties of an Interface that exist in the Interface

自古美人都是妖i 提交于 2020-01-16 08:19:31

问题


So I'm trying to serialize only those properties of an interface that exist in the interface, not the underlying type itself.

To that end, by following this, I've written the following code:

public static IEnumerable<T> ToInterfacedObjects<T>(this IEnumerable<T> data) where T : class
{
    var list = new List<T>();
    var properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
    foreach (var datum in data)
    {
        var moq = new Mock<T>();
        foreach (var propertyInfo in properties)
        {
            var expressionParameter = Expression.Parameter(typeof(T));
            var expressionProperty = Expression.Property(expressionParameter, propertyInfo);
            var expressionConversion = Expression.Convert(expressionProperty, typeof(object));
            var expressionLambda =
                Expression.Lambda<Func<T, object>>(expressionConversion, expressionParameter);

            moq.SetupGet(expressionLambda).Returns(datum);
        }
        list.Add(moq.Object);
    }

    return list;
}

The problem is, I'm getting

System.ArgumentException: 'Expression is not a property access: => (object).ReportName'

On line moq.SetupGet(expressionLambda).Returns(datum);.

ReportName is one of the properties in IReport. I'm trying to serialize an IEnumerable<IReport> that under the hood contains List<Report>, but I don't want everything in Report to be serialized.

public interface IReport
{
    string ReportName { get; }
    string ReportSubject { get; }
    string ReportType { get; }
    string FilesUrl { get; }
    ReportStatus Status { get; }
    decimal LastRunDate { get; }
    decimal LastRunTime { get; }
    string UserCreated { get; }
    decimal DateCreated { get; }
    string UserUpdated { get; }
    decimal DateUpdated { get; }
    string DistListAdmin { get; }
    decimal DistListUpdateDate { get; }
    string DistListUpdateUser { get; }
}

What am I doing wrong?

来源:https://stackoverflow.com/questions/59619731/serialize-only-those-properties-of-an-interface-that-exist-in-the-interface

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!