1 // Copyright 2004-2007 Castle Project - http://www.castleproject.org/
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
7 // http://www.apache.org/licenses/LICENSE-2.0
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
15 namespace Castle
.DynamicProxy
.Builder
.CodeBuilder
.SimpleAST
18 using System
.Reflection
.Emit
;
20 using Castle
.DynamicProxy
.Builder
.CodeBuilder
.Utils
;
23 /// Summary description for ConvertExpression.
26 public class ConvertExpression
: Expression
29 private Type _fromType
;
30 private Expression _right
;
32 public ConvertExpression( Type targetType
, Expression right
) : this(targetType
, typeof(object), right
)
36 public ConvertExpression( Type targetType
, Type fromType
, Expression right
)
43 public override void Emit(IEasyMember member
, ILGenerator gen
)
45 _right
.Emit(member
, gen
);
47 if (_fromType
== _target
)
52 if (_fromType
.IsByRef
)
54 throw new NotSupportedException("Cannot convert from ByRef types");
59 throw new NotSupportedException("Cannot convert to ByRef types");
62 if (_target
.IsValueType
)
64 if (_fromType
.IsValueType
)
66 throw new NotImplementedException("Cannot convert between distinct value types at the moment");
71 // Assumes fromType is a boxed value
72 gen
.Emit(OpCodes
.Unbox
, _target
);
73 OpCodeUtil
.EmitLoadIndirectOpCodeForType(gen
, _target
);
78 if (_fromType
.IsValueType
)
81 gen
.Emit(OpCodes
.Box
, _fromType
);
82 EmitCastIfNeeded(typeof(object), _target
, gen
);
87 EmitCastIfNeeded(_fromType
, _target
, gen
);
92 private void EmitCastIfNeeded(Type
from, Type target
, ILGenerator gen
)
94 if (target
.IsSubclassOf(from))
96 gen
.Emit(OpCodes
.Castclass
, target
);