سؤال

This would be very simple.

public class ModelMapNode { }

public class ModelMapNode<TModelMap> : ModelMapNode { }

public class ModelMapView { }

public class ModelMapView<TModelMap> : ModelMapView
    where TModelMap : ModelMapNode
{
    public ModelMapView()
    {
        this.RemovedProperties = new List<Expression<Func<TModelMap, object>>>();
    }

    public List<Expression<Func<TModelMap, object>>> RemovedProperties { get; private set; }

    public void RemoveNode<TNodeModelMap>(Expression<Func<TModelMap, TNodeModelMap>> expression)
        where TNodeModelMap : ModelMapNode
    {
        this.RemovedProperties.Add(expression);
    }
}

Theoretically it would be possible to assign any generic type in an object. But the way I did, the assignment is invalid.

I can not assing an Expression<Func<T, T2>> in a Expression<Func<T, object>>.

It is possible?

هل كانت مفيدة؟

المحلول

I'm not sure what you're trying to accomplish here (you haven't explained why you need to store a weaker type than you expose through your API), but to answer your question as asked, you can do:

Expression<Func<TModelMap, TNodeModelMap>> source = ...

var convertedBody = Expression.Convert(source.Body, typeof(object));    

var convertedExpression = Expression.Lambda<Func<TModelMap, object>>
                          (convertedBody, source.Parameters);

RemovedProperties.Add(convertedExpression);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top