2 回答

TA貢獻(xiàn)1818條經(jīng)驗 獲得超11個贊
可以使用表達(dá)式訪問器替換該類型。
class ParameterRewriter<T, U> : ExpressionVisitor
{
protected override Expression VisitParameter(ParameterExpression node)
{
if (node.Type.Equals(typeof(T)))
{
return Expression.Parameter(typeof(U), node.Name);
}
return base.VisitParameter(node);
}
protected override Expression VisitMember(MemberExpression node)
{
if (node.Expression is ParameterExpression paramExp && paramExp.Type.Equals(typeof(T)))
{
return Expression.MakeMemberAccess(
Expression.Parameter(typeof(U), paramExp.Name),
typeof(U).GetMember(node.Member.Name).Single());
}
return base.VisitMember(node);
}
protected override Expression VisitLambda<L>(Expression<L> node)
{
var parameters = node.Parameters.ToList();
var found = false;
for (var i = 0; i < parameters.Count; i++)
{
if (parameters[i].Type.Equals(typeof(T)))
{
parameters[i] = Expression.Parameter(typeof(U), parameters[i].Name);
found = true;
}
}
if (found)
{
return Expression.Lambda(node.Body, parameters);
}
return base.VisitLambda(node);
}
}
在這種情況下,創(chuàng)建一個實例并訪問原始表達(dá)式樹,您將獲得所需的內(nèi)容。擴(kuò)展方法可能更具可讀性:new ParameterRewriter<DocumentTypeA, DocumentTypeB>()
public static class ExpressionExtensions
{
public static Expression<Func<U, R>> RewriteParameter<T, U, R>(this Expression<Func<T, R>> expression)
{
var rewriter = new ParameterRewriter<T, U>();
return (Expression<Func<U, R>>)rewriter.Visit(expression);
}
}
用法很簡單:
Expression<Func<A, bool>> expA = x => x.Id == 1;
Expression<Func<B, bool>> expB = expA.RewriteParameter<A, B, bool>();

TA貢獻(xiàn)1829條經(jīng)驗 獲得超9個贊
使用兩個類都繼承的接口,并包含兩個類中相同的屬性,例如
interface IDocumentTypes
{
string AString { get; set; } //indicates that both classes need to implement this
//etc...
}
class DocumentTypeA : IDocumentTypes
{
//your class
}
然后,您的兩個類都可以在實現(xiàn)接口時使用,并且仍然是強(qiáng)類型。除了實現(xiàn)接口中定義的屬性/函數(shù)之外,這些類不需要有任何共同點。ExpressionIDocumentTypes
- 2 回答
- 0 關(guān)注
- 108 瀏覽
添加回答
舉報