问题
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