forked from aspnet/AspNetWebStack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDynamicWrapper.cs
More file actions
83 lines (69 loc) · 2.9 KB
/
Copy pathDynamicWrapper.cs
File metadata and controls
83 lines (69 loc) · 2.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Dynamic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
namespace System.Web.Helpers.Test
{
/// <summary>
/// Dynamic object implementation over a regualar CLR object. Getmember accesses members through reflection.
/// </summary>
public class DynamicWrapper : IDynamicMetaObjectProvider
{
private object _object;
public DynamicWrapper(object obj)
{
_object = obj;
}
public DynamicMetaObject GetMetaObject(Expression parameter)
{
return new DynamicWrapperMetaObject(parameter, this);
}
private class DynamicWrapperMetaObject : DynamicMetaObject
{
public DynamicWrapperMetaObject(Expression expression, object value)
: base(expression, BindingRestrictions.Empty, value)
{
}
private object WrappedObject
{
get { return ((DynamicWrapper)Value)._object; }
}
private Expression GetDynamicExpression()
{
return Expression.Convert(Expression, typeof(DynamicWrapper));
}
private Expression GetWrappedObjectExpression()
{
FieldInfo fieldInfo = typeof(DynamicWrapper).GetField("_object", BindingFlags.NonPublic | BindingFlags.Instance);
Debug.Assert(fieldInfo != null);
return Expression.Convert(
Expression.Field(GetDynamicExpression(), fieldInfo),
WrappedObject.GetType());
}
private Expression GetMemberAccessExpression(string memberName)
{
return Expression.Property(
GetWrappedObjectExpression(),
memberName);
}
public override DynamicMetaObject BindGetMember(GetMemberBinder binder)
{
var binderDefault = binder.FallbackGetMember(this);
var expression = Expression.Convert(GetMemberAccessExpression(binder.Name), typeof(object));
var dynamicSuggestion = new DynamicMetaObject(expression, BindingRestrictions.GetTypeRestriction(Expression, LimitType)
.Merge(binderDefault.Restrictions));
return binder.FallbackGetMember(this, dynamicSuggestion);
}
public override IEnumerable<string> GetDynamicMemberNames()
{
return (from p in WrappedObject.GetType().GetProperties()
orderby p.Name
select p.Name).ToArray();
}
}
}
}