Is it possible to have an array of unknown types?

public static bool Compare<T>(this T source, T other, params Expression<Func<T>>[] propertiesToSkip)
{
    PropertyInfo[] sourceProperties = source.GetType().GetProperties();
    List<string> lstPropertiesToSkip = (from x in propertiesToSkip select ((MemberExpression)((UnaryExpression)x.Body).Operand).Member.Name).ToList();
    return !(sourceProperties.Any(sourcePropertyInfo => !lstPropertiesToSkip.Contains(sourcePropertyInfo.Name) && (!sourcePropertyInfo.GetValue(source, null).Equals(sourcePropertyInfo.GetValue(other, null)))));
}

I want this feature to be called.

var source = new MyClass();
var other = new MyClass();
source.Compare<MyClass>(other, ()=>SkipProperty1, ()=>SkipProperty2);

Problem :() => SkipProperty1 and () => SkipProperty2 are not of type MyClass. I need:

Compare <A,B,C,D...>  
params Expression<Func<T>>[] where T is A,B,C,D,E...

I looked at AutoMapper with smooth syntax.

public IMappingExpression<TSource, TDestination> ForMember(string name, Action<IMemberConfigurationExpression<TSource>> memberOptions);

Mapper.CreateMap<MyClass, MyClass>()
            .ForMember(dest => dest.Property1, opt => opt.Ignore())
            .ForMember(dest => dest.Property2, opt => opt.Ignore()));

- Can I change the signature of Compare to make the function work?

- Is there any other way to solve this? For example, using free syntax

Note. I do not want to send property names as strings.

+3
source share
1 answer

One option is to change the signature of your arguments paramto lambda expressions that return object. Something like that:

public static bool Compare<T>
  (this T source, T other, params Expression<Func<object>>[] propertiesToSkip)

, .NET . , PropertyInfo - ( ).

. - :

class SkipComparison<T> {
  public T Source { get; set; }
  public T Other { get; set; }
  public List<PropertyInfo> PropertiesToSkip { get; set; }

  public SkipComparison<T> Skip<R>(Expression<Func<R>> f)
    // TODO: Extract property info, add it to 
    // 'PropertiesToSkip' and 'return this;'
  public bool Run()
    // TODO: Actually perform the comparison here
}

Compare Source Other, Skip .

+2

Source: https://habr.com/ru/post/1793856/


All Articles